XML Serialisation - When To Use DataContractSerializer / Binary / XMLSerialiser

為{幸葍}努か 提交于 2019-12-18 13:37:31

问题


I ve been looking at this for a while now

It seems that binary serialisation is discouraged as any change to field names breaks serialisation =? Not Good

XMLSerializer is problematic because you have to provide a no arg constructor and public fields although you do have more control over elements being attributes or elements and their naming

DataContractSerializer is good but all suclassses need to be explicitly added which is a shame

However I stumbled across NetDataContractSerializer which does not have this limitation.

If your goal is C# serialisation and no big constraints on size of xml is NetDataContractSerializer always the way to go here??


回答1:


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....




回答2:


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).



来源:https://stackoverflow.com/questions/1977043/xml-serialisation-when-to-use-datacontractserializer-binary-xmlserialiser

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