Search code examples
c#xmlrestwcf

XML Serializer not creating attributes


I have a simple API

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "movex/anp_prd")]
Producer Test2();

And a simple class

public class Producer
{
    [XmlAttribute]
    public int Test { get; set; }

    [XmlElement]
    public string ProducerFound { get; set; }
}

When I call the API I'm just create a class for test purposes

public Producer Test2()
{
    return new Producer
    {
        Test = 999,
        ProducerFound = "Yes"
    };
}

The response is:

<Producer xmlns="http://schemas.datacontract.org/2004/07/HSL.FOPS.WCFService.DataTransferObjects" 
       xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
   <ProducerFound>Yes</ProducerFound>
   <Test>999</Test>
</Producer>

I can't figure out why the Test property is not an attribute of Producer in the XML


Solution

  • WCF uses DataContractSerializer by default; add an XmlSerializerFormat attribute to your service contract (or individual operation contracts) to instruct WCF to use XmlSerializer instead.

    https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/using-the-xmlserializer-class