0

I have created a REST Service which sends a response in XML. I have set the response format as XML and created the following Data Contracts:

    [DataContract]
    public class AuthorisationResult
    {
        [DataMember]
        public string Status { get; set; }

        [DataMember]
        public Variable[] Variables { get; set; }
    }


    [DataContract]
    public class Variable
    {
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public string Type { get; set; }
    }

This works ok however the output of the XML is not formatted as I need it. It is showing like this:

<Variables>
        <Variable>
            <Name>SomeName1</Name>
            <Type>SomeType1</Type>
        </Variable>
</Variables>

But I want to show it like this:

 <Variables>
        <Variable Name="SomeName1" Type="SomeType1"/>
 </Variables>

Can anyone advise what I change to structure it how I want.

  • Does this answer your question? [Serialize Property as Xml Attribute in Element](https://stackoverflow.com/questions/11330643/serialize-property-as-xml-attribute-in-element) – Pac0 Mar 04 '20 at 14:41
  • Does this answer your question? [DataContract XML serialization and XML attributes](https://stackoverflow.com/questions/4858798/datacontract-xml-serialization-and-xml-attributes) – Heretic Monkey Mar 04 '20 at 14:46

1 Answers1

0

Just add XmlAttribute to the properties

[DataContract]
public class Variable
{
    [DataMember, XmlAttribute]
    public string Name { get; set; }

    [DataMember, XmlAttribute]
    public string Type { get; set; }
}
Krishna Varma
  • 4,238
  • 2
  • 10
  • 25