C# - Differences between DataContractSerializer and XmlSerializer

Once again I had this discussion at work. What is the difference between DataContractSerializerand XmlSerializer? Why use one of them over the other? The two serializers are very different and tackle XML serialization in different ways.

XML serialization has not seen much love from Microsoft over the last many years. Most likely due to most modern applications using JSON instead (Json.Net for example). However XML is still used quite a lot - especially when integrating with older systems. Without using third party libraries you are stuck using XmlSerializer or DataContractSerializer.

Here I will list some of the differences between the two:

XmlSerializer
  • Serializes all public members - except if told not to - using [XmlIgnore]. It is "opt out".
  • Does not Serialize DateTimeOffset without minor hacks (this has caught me off guard multiple times).
DataContractSerializer
  • Works for both JSON and XML (JSON using DataContractJsonSerializer)
  • Requires XML to be in a specific order - as the order of elements in XML has significance (XmlSerializer ignores this). Alternatively an order can be specified.
  • Does not support XML attributes such as <xml attribute="will not be serialized"></xml>.
  • Only serializes members marked as [DataMember]. It is "opt in"
  • Can Serialize private members.

So what does the above mean? Both classes have caveats. The worst thing about the XmlSerializer is that there is no support for DateTimeOffset. If you do not use this you are good to go. Otherwise there are workarounds for this. You can also avoid annotations for your properties most of the time - unlike DataContractSerializer where you will have to add DataContract and DataMember to your objects.

The biggest downside of the DataContractSerializer is that it cares about the sequence of elements. I have never implemented any API where the order of XML elements have a significance. This is dangerous as it throws no exception if the XML is out of sequence. It just skips it. However if you are aware of this it might not be a problem for you.

On the other hand you can reuse the DataContractSerializer for serialization of JSON. Whereas XmlSerializer is XML specific. If you prefer using opt-in (only serializing what you want) then DataContractSerializer might be just right for you.

Did I forget anything? Let me know in the comments! :)