What is the suggested way to investigate XML recursively?
XMLReader
/ XMLDocument
/XMLTextReader
/other option ?
I'm a little bit confused why we have so much ways to read XML.
Important Note: I have a constraint which is the Xml reading object should be able to create itself from a given Stream
reference object.
Both XDocument
and XmlDocument
support random access of the document and therefore support bi-directional traversing of the node hierarchy. Therefore, either of those would be good choices for a recursive method.
XDocument
is designed for working with LINQ whereas XmlDocument
is more convenient when querying the document with XPath. It's really a matter of preference and what you need at the time. Both are equally valid options and provide very similar functionality.
XMLTextReader
is more efficient because it simply reads one node at a time from a stream, without validating the entire document graph. However, it is forward-only, so you can't traverse back up a node tree to get back to a parent node, therefore it's probably not a good choice for what you are doing.
XMLReader
is the abstract base class for the XMLTextReader
(among others), so it cannot be used directly.
UPDATE
Since you mentioned in a comment, above, that all you are really trying to do is find all the leaf elements, you don't really need to use recursion at all. You can take advantage of LINQ or XPath to do all the work for you. Since you said you didn't want to use LINQ, here's how to do it with XPath via XmlDocument
:
XmlNodeList leafElements = doc.SelectNodes("//*[not(node())]");
Or with XDocument
:
IEnumerable<XElement> leafElements = doc.XPathSelectNodes("//*[not(node())]");