The most efficient way to parse Xml The most efficient way to parse Xml xml xml

The most efficient way to parse Xml


The three most common methods to read are:

XmlDocumentIt reads the whole file in a tree structure that can then be accessed using XPath or by browsing all the nodes. It requires a lot of memory for very large file since the whole XML structure must be loaded in memory. Very good and simple to use for smaller files (less then a few megs).

XmlReaderFast, but also a real pain to use since it's sequential. If you ever need to go back, you can't, and XML structure are usually very prone to having disorganised orders. Also, if you read from a non ending stream of XML, this is probably the only way to go.

XML serializersThis basically does everything for you, you provide the root object of your model and it creates and read the XML for you. However, you have almost no control over the structure, and reading older versions of your object is a pain. So this won't work very well for persistance.

XDocument and LINQ to XMLAs Daniel Straight pointed out. But I don't know it enough to comment. I invite anyone to edit the post and add the missing info.


Now writing is another story. It's a pain to maintain a XmlDocument and XmlWriter is a breeze to use.

I'd say, from my experience, that the best combo is to write using XmlWriter and read using XmlDocument.


There's also XDocument and LINQ to XML, which I consider by far the most efficient when it comes to programmer time.


The fastest one would be XmlTextReader. From MSDN:

"Represents a reader that provides fast, non-cached, forward-only access to XML data."

More here: XmlTextReader Class

Though it really depends on the problem to decide which "method" would be most apropriate for use. If you need to read an XML file only once (e.g.: reading and caching some global app-settings, etc.), then XmlTextReader is the winner. But remember, it is forward-only-reader. If you need to search/modify all-over the XML, then you should probably use XmlDocument Class.