XML Serialisation - When To Use DataContractSerializer / Binary / XMLSerialiser

南楼画角 提交于 2019-11-30 09:55:04

Dan Rigsby has a really good comparative article on XmlSerializer vs. DataContractSerializer and also touches on the NetDataContractSerializer.

DataContractSerializer:

  • it's fast - around 10% faster than XmlSerializer
  • it's interoperable - works flawlessly with Java, Ruby - you name it
  • uses explicit "opt-in" model - you need to mark what gets serialized
  • doesn't require any constructor
  • can serialize non-public members and internal fields
  • doesn't support attributes on XML nodes

You tell the DCS explicitly what to serialize, but you don't have much influence over how it's done.

XmlSerializer

  • serializes only public fields and properties
  • serializes everything except those you exclude (opt-out model)
  • support attributes and everything
  • it's interoperable - works flawlessly with Java, Ruby - you name it
  • requires a parameterless constructor for deserialization

You tell the XmlSerializer pretty clearly how and what to serialize, but you cannot serialize everything - only publicly visible properties.

The NetDataContractSerializer is a bit of an oddity - it's not interoperable, it works only if both ends are .NET - it includes .NET type information into the message (making it bigger). You cannot add it declaratively to a WCF service "out of the box".

It's a tough trade-off - as always. Definitely stay away from any binary formatter - that's not backwards compatible, brittle, and bound to give you headaches - use one of those standard ways of doing it. Which one is the "best" for your given scenario is really hard to tell - you'll have to figure that one out for yourself....

Marc Gravell shows on his blog the results of a benchmark he did with DataContractSerializer, XmlSerializer, and most of the other .NET serializers around, including protobuf-net (an implementation of Protocol Buffers for .NET he created).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!