Sujith Kp
Sujith Kp

Reputation: 1105

how can i serialize a property to element with a default attribute

I need to serialize this class with a property to xml, the property need to come as an element with the name of property as value for an default attribute.

class RequestDto
{
    public string ZipCode {get;set;}
} 

as 

<RequestDto>
    <Parameter name="zipcode"> </Parameter>
</RequestDto>

Upvotes: 2

Views: 43

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062650

You can't do that via XmlSerializer directly from the shape of that object model; basically, XmlSerializer assumes that your model and xml will be more or less the same. Implementing IXmlSerializable is frankly not worth it. I would suggest using XDocument to serialize that instead:

string zip = "abc";
var el = new XElement("RequestDto",
    new XElement("Parameter",
        new XAttribute("name", "zipcode"),
        zip
    )
);

Which gives (via .ToString()):

<RequestDto>
  <Parameter name="zipcode">abc</Parameter>
</RequestDto>

Upvotes: 3

Related Questions