3

I want to get all the children from given node till leaves without using recursion. Is that possible? I know how to do it in LINQ to XML, but have some problems with XmlNode:S

Nickon
  • 9,652
  • 12
  • 64
  • 119

2 Answers2

6

You can use the SelectNodes method along with an XPath expression that selects all descendants:

XmlNodeList result = myXmlNode.SelectNodes("descendant::node()");

Make sure to use the other overload if you want to filter more specifically and need to supply any namespace prefixes.

Update: This will only select non-attribute nodes as your question doesn't ask for attributes. It's possible by modifying the XPath expression, though:

XmlnodeList result = myXmlNode.SelectNodes("descendant::node() | descendant::*/@*");
O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114
1

You can either use recursion or an XPath expression:

I'm not very good at XPath but something like:

 var nodes = myDoc.SelectNodes("//*");  

(edit: this one seems to work)

H H
  • 263,252
  • 30
  • 330
  • 514
  • Only for elements, though. Other kinds of nodes will not be selected by `*`. – O. R. Mapper Aug 02 '12 at 14:18
  • 1
    Also, have you tried this from an arbitrary node in the middle of the document, or just from the root node? I didn't and the documentation wasn't explicit on this, but usually `//` means that everything from the root is considered, not just the current subtree. – O. R. Mapper Aug 02 '12 at 14:20