Search code examples
c#xmlxsdlinq-to-xmlxmlserializer

Create XML using XDocument or from XSD schema using xsd.exe and XmlSerializer?


Why use xsd.exe tool to create class for XSD schema and then use serializer to create XML file, when you can use XDocument.

Should I be always using XDocument and manually create the XML document by nesting XElement elements, or is there something I am not seeing that makes using XSD schema and XmlSerializer better.


Solution

  • XDocument and XmlSerializer/xsd.exe are useful for different sorts of things.

    When you're dealing with a large XML document, you should really have an XSD schema. This is an agreement between all parties on what the structure of the XML document should be, what properties / children / data types, it has etc.

    If you have an XSD, then you might as well use it to generate C# classes. You could hand-write XDocument code, but then you need to keep referring back to the XSD to see what properties / children you should be accessing, and what their data types are. If the XSD changes, you have to go and manually search through your XDocument code looking for things which need to be changed.

    If instead you generate C# classes, then the properties you can access, and their data types, are right there in the type system: you don't need to refer to the XSD. If the XSD changes, you can re-generate your C# classes and get compiler errors in places you need to change.

    If you have an XSD, you should also validate that XML documents you receive match that XSD, see e.g. this answer.

    XmlSerializer is often also more efficient than XDocument.

    However, sometimes you need to work with someone else's XML document, and either there's no XSD or the generated C# classes are far more complex than you need. Or sometimes you're just doing something very simple and it's not worth writing an XSD. Or sometimes the XML does something really annoying which doesn't map well to C# classes. In those cases, using XDocument is often the better choice.

    (The one thing you should avoid at all costs is XmlDocument -- that does the same thing as XDocument, but much worse.)