Select first result in XPath

xpath

I've looked at this question: Select first instance only with XPath?

But if I have a node-set like this:


<container value="">
  <data id="1"></data>
  <data id="2">test</data>
  <container>
    <data id="1">test</data>
    <data id="3">test</data>
  </container>
</container>

Now my scenario is that this node-set is deep inside a document, and I have a pointer to the inner container. So I have to prefix my XPath with "/container/container" (the path is actually longer, but for this example this should do).

EDIT:
What I want is a "data" node with an id of 1, which should come from the lowest node first or the closest ancestor. So, if I can't find it on the "current" (/container/container) I should look at the ancestors and get the nearest one (or in the end, not find anything). I have tried this:

/container/container/ancestor-or-self::container/data[@id="1"]

Which brings back a result set with two nodes. I thought I could use last() to get the deepest one, so I tacked that on the end, but to no avail.

Best Answer

Make sure the last() is scoped correctly. Try:

(/container/container/ancestor-or-self::container/data[@id="1"])[last()]

Similarly:

//container[last()]

and:

(//container)[last()]

are not the same thing. The first will return the last container node at each level of the hierarchy - multiple matches - and the second will return the last container node found - one match.

Related Topic