Nickon
Nickon

Reputation: 10156

Get all descendants of given XmlNode

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

Upvotes: 3

Views: 6846

Answers (2)

O. R. Mapper
O. R. Mapper

Reputation: 20770

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::*/@*");

Upvotes: 6

Henk Holterman
Henk Holterman

Reputation: 273631

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)

Upvotes: 1

Related Questions