Nowadays, what's the best way to serialize/deserialize domain objects into an xml document? XmlSerializer or Linq To XML? What are the pros and cons of each solution?
-
Ops... only now I've realized that I wrote "Linq To Objects" instead of "Linq To XML"... :P – Notoriousxl Jun 20 '11 at 18:17
1 Answers
Here's the main benefit I see for using Linq to XML nowadays.
XmlSerializer requires a default (parameter-less) constructor. So, if you're doing any kind of inversion of control and passing dependencies into your class via the constructor, you'll need to also have a default constructor that bypasses the injection of those dependencies. That kinda defeats the whole purpose of using constructor injection.
Of course, with Linq to XML, you'll need to write your own serialization code, but I've done that with either a set of methods like FromXml
and ToXml
or simply an Xml
property with getter and setter that do the serialization of exactly the fields that need to be saved. I like having that control in code instead of having to use attributes on some properties to have them ignored.

- 13,642
- 9
- 69
- 105
-
My "XmlSerializer objects" are not so important: I'm only using them as helper classes to implement my IRepository
interfaces, so they are "invisible" outside the Data Access Layer. :) I guess my solution is similar to yours: the base class XmlRepository – Notoriousxl Nov 28 '11 at 20:09(TXmlTag is a "XmlSerializer object") have two protected abstract "Convert" methods... TXmlTag Convert(TDomainObject entity); TDomainObject Convert(TXmlTag tag); Perhaps I could write linq queries directly in Convert methods without having to write a lot of extra mapping classes...