Can I get an XPathNodeIterator directly from an XPath?

Posted by Val on Stack Overflow See other posts from Stack Overflow or by Val
Published on 2010-04-28T03:09:59Z Indexed on 2010/04/28 3:13 UTC
Read the original article Hit count: 228

I hope I'm just missing something obvious. I have a number of repeating nodes in an XML document:

<root>
  <parent>
    <child/>
    <child/>
  </parent>
</root>

I need to examine the contents of each of the <child> elements in turn, so I need an XPathNodeIterator containing the nodeset of all the <child> nodes.

If I have an XPath that would select the child nodes, e.g. /root/parent/child, is there any way to feed that directly to a new XPathNodeIterator? Everything I see in the docs and examples indicates I have to first get an XPathNavigator to the <parent>, then Select the child nodes, like:

XPathNavigator nav = datasource.CreateNavigator().SelectSingleNode( "/root/parent" );
XPathNodeIterator it = nav.Select( "./child" );
foreach ( child in it ) { /* do something */ }

I was hoping to skip the XPathNavigator, and intialize the XPathNodeIterator with XPath to the child nodes directly, something like:

XpathNodeIterator it = new XpathNodeIterator("/root/parent/child");
foreach ( child in it ) { /* do something */ }

Possible? The benefit is not only saving a line of code, but I can use a single XPath expression, rather than splitting the path to the <child> nodes in two, first to get the parent element, then to select its children.

© Stack Overflow or respective owner

Related posts about xpathnavigator

Related posts about xpathnodeiterator