Compartilhar via


DataContractSerializer: A better XMLSerializer

XMLSerializer provides a simple means of serializing and deserializing object graphs to and from XML. However, simplicity brings a price, and there are limitations that I have seen people come up against.

The most common of these is that XMLSerializer will only work on public properties and needs setters to be able to deserialized, and this can create awkward design decisions - such as exposing properties that you really don't want to just to enable serialization. The second common obstacle is that there are no hooks to detect when a class is being constructed during deserialization - this is sometimes necessary when special work needs to be done (or not done) during deserialization.

It is possible to customize serialization by implementing IXmlSerializable - problematic (and undocumented) in .NET 1.1 but much improved in .NET 2.0. However this can create a lot of extra work and maintenance that is a real pain.

With the arrival of Windows Communication Foundation in .NET FX 3.0, an alternative is available that you might consider. The DataContractSerializer (DCS - renamed from XmlFormatter in the betas) provides an Xml Serializer than can be used independantly of WCF.

The key differences are:

  • Hooks are providing for refining control of (de)serialization - particularly useful for handling versioning issues. By applying any of four special attributes to methods in the target class you can have them called either before or after (de)serialization.
  • The serializer is "opt-in" rather than "opt-out" - which makes (imho) for much cleaner code. In XmlSerializer you could use XmlIgnore to have the serializer ignore certain properties. With the DCS you explicitly mark what you want to serialize.
  • Finally, ANY field or property can be serialized - even if they are marked private.

Check out DataContractSerializer in the SDK!

Comments