I am now learning XmlDocument but I’ve just ran into XDocument and when I try to search the difference or benefits of them I can’t find something useful, could you please tell me why you would use one over another ?
I am now learning XmlDocument but I’ve just ran into XDocument and when I
Share
If you’re using .NET version 3.0 or lower, you have to use
XmlDocumentaka the classic DOM API. Likewise you’ll find there are some other APIs which will expect this.If you get the choice, however, I would thoroughly recommend using
XDocumentaka LINQ to XML. It’s much simpler to create documents and process them. For example, it’s the difference between:and
Namespaces are pretty easy to work with in LINQ to XML, unlike any other XML API I’ve ever seen:
LINQ to XML also works really well with LINQ – its construction model allows you to build elements with sequences of sub-elements really easily:
It’s all a lot more declarative, which fits in with the general LINQ style.
Now as Brannon mentioned, these are in-memory APIs rather than streaming ones (although
XStreamingElementsupports lazy output).XmlReaderandXmlWriterare the normal ways of streaming XML in .NET, but you can mix all the APIs to some extent. For example, you can stream a large document but use LINQ to XML by positioning anXmlReaderat the start of an element, reading anXElementfrom it and processing it, then moving on to the next element etc. There are various blog posts about this technique, here’s one I found with a quick search.