Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlTextReader vs. XDocument

Tags:

I'm in the position to parse XML in .NET. Now I have the choice between at least XmlTextReader and XDocument. Are there any comparisons between those two (or any other XML parsers contained in the framework)?

Maybe this could help me to decide without trying both of them in depth.

The XML files are expected to be rather small, speed and memory usage are a minor issue compared to easiness of use. :-)

(I'm going to use them from C# and/or IronPython.)

Thanks!

like image 207
MarkusSchaber Avatar asked Nov 11 '11 15:11

MarkusSchaber


People also ask

What is the difference between XmlDocument and XDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.

What's the difference between XmlDocument and XmlReader?

XmlDocument is very easy to use. Its only real drawback is that it loads the whole XML document into memory to process. Its seductively simple to use. XmlReader is a stream based reader so will keep your process memory utilization generally flatter but is more difficult to use.

What is XDocument C#?

The XDocument class contains the information necessary for a valid XML document, which includes an XML declaration, processing instructions, and comments. You only have to create XDocument objects if you require the specific functionality provided by the XDocument class.


1 Answers

If you're happy reading everything into memory, use XDocument. It'll make your life much easier. LINQ to XML is a lovely API.

Use an XmlReader (such as XmlTextReader) if you need to handle huge XML files in a streaming fashion, basically. It's a much more painful API, but it allows streaming (i.e. only dealing with data as you need it, so you can go through a huge document and only have a small amount in memory at a time).

There's a hybrid approach, however - if you have a huge document made up of small elements, you can create an XElement from an XmlReader positioned at the start of the element, deal with the element using LINQ to XML, then move the XmlReader onto the next element and start again.

like image 88
Jon Skeet Avatar answered Jan 03 '23 00:01

Jon Skeet