How can you control .NET DataContract serialization so it uses XML attributes instead of elements?

.net, datacontract, serialization, xml-serialization

Solution

You can't do this with the `DataContractSerializer`; if you want attributes you need to use the `XmlSerializer` instead. With the `DataContractSerializer` class 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 `XmlSerializerFormatAttribute` which allows you to use the `XmlSerializer` for serialization.

Problem

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?

Original source