XPath relative selection using XmlNode (C #)

Let's say I have the following XML file:

<a>
  <b>
    <c></c>
  </b>
  <b>
    <c></c>
  </b>
</a>

var nodes = doc.SelectNodes("/a/b");

      

will select two nodes b.

Then I will loop over these two nodes, for example:

 foreach (XmlNode node in nodes) { }

      

However, when I call node.SelectNodes("/a/b/c");

, it still returns both values, not just the descendants. Is it possible to select nodes only descending from the current one node

?

+2


a source to share


3 answers


In the loop, foreach

you already know what node

is /a/b

in the original document - so to get only its children, c

just use relative xpath:



node.SelectNodes("c")

      

+8


a source


you can use node.SelectSingleNode("C");



+2


a source


/a/b[1]/c

      

For intance, gets a nodelist of all children of the first b that have a c tag.

To get the first c as a single-leaf nodelist, use / a / b [1] / c [1] ./ a / b / c [1] returns a multi-node nodelist again.

SelectSingleNode is probably misleading as far as I know XPath always returns a nodelist, which may optionally contain one node (or even be empty).

// c [1] just selects the first c in the document.

+1


a source







All Articles