Ian Ringrose
Ian Ringrose

Reputation: 51927

How do I choose between Xml serialization, DataContractSerializer and LINQ to XML for serializing a tree of simple objects?

I need to serialize a tree of simple objects as XML to/from a file – the world has changed since I last had to do this…

(I don’t care about the schema of the XML provided a support person can understand the file if needed)

So what are the trade off to consider when choosing between the different “easy xml” APIs in .net?

Upvotes: 4

Views: 626

Answers (2)

Ian Ringrose
Ian Ringrose

Reputation: 51927

This is how I have come to think about the options:

LINQ to XML – full control over the XML and the design of the objects, the most code of any of the 3 options.

DataContractSerializer – little or no control over the XML, can cope with most objects

XmlSerializer – full control over the XML, but you must design the objects in a way that Xml Serialization likes.

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1064274

DataContractSerializer doesn't necessarily emit "typical" xml, and you don't have much control over the output. It does, however, support full-graphs if you need. If you want xml, and don't need full-graphs, I would tend towards XmlSerializer - it'll avoid having to write any code for manually traversing the data (ala XmlDocument or XDocument), yet give you control.

One caveat: XmlSerializer places demands on your type (public, public parameterless constructor, limited to public members, no serialization callbacks, etc). They are usually not a problem.

But then, I'd probably be writing binary instead of xml anyway ;p (just not with BinaryFormatter, which has.... kinks).

Upvotes: 3

Related Questions