If I have a class marked as a DataContract and a few properties on it marked with DataMember attributes I can serialize it out to XML easily, but it would create output like:
<Person> <Name>John Smith</Name> <Email>john.smith@acme.com</Email> <Phone>123-123-1234</Phone> </Person>
What I would prefer is attributes, like…
<Person Name='John Smith' Email='john.smith@acme.com' Phone='123-123-1234' />
The DataMember attribute allows me to control the Name and Order but not whether it is serialized as an element or attribute. I have looked around and found DataContractFormat and IXmlSerializable but I am hoping there is there an easier solution.
What is the easiest way to do this?
You can’t do this with the
DataContractSerializer; if you want attributes you need to use theXmlSerializerinstead. With theDataContractSerializerclass a more restrictive subset of the XML specification is permitted which improves performance, and improves the interoperability of published services, but gives you rather less control over the XML format.If you’re using WCF services then take a look at
XmlSerializerFormatAttributewhich allows you to use theXmlSerializerfor serialization.