Find position of a node within a nodeset using xpath

Posted by Phil Nash on Stack Overflow See other posts from Stack Overflow or by Phil Nash
Published on 2010-04-09T09:11:41Z Indexed on 2010/04/09 9:23 UTC
Read the original article Hit count: 348

Filed under:
|
|
|

After playing around with position() in vain I was googling around for a solution and arrived at this older stackoverflow question which almost describes my problem.

The difference is that the nodeset I want the position within is dynamic, rather than a contiguous section of the document.

To illustrate I'll modify the example from the linked question to match my requirements. Note that each <b> element is within a different <a> element. This is the critical bit.

<root>
    <a>
        <b>zyx</b>
    </a>
    <a>
        <b>wvu</b>
    </a>
    <a>
        <b>tsr</b>
    </a>
    <a>
        <b>qpo</b>
    </a>
</root>

Now if I queried, using XPath for a/b I'd get a nodeset of the four <b> nodes. I want to then find the position within that nodeset of the node that contains the string 'tsr'. The solution in the other post breaks down here: count(a/b[.='tsr']/preceding-sibling::*)+1 returns 1 because preceding-sibling is navigating the document rather than the context node-set.

Is it possible to work within the context nodeset?

© Stack Overflow or respective owner

Related posts about Xml

Related posts about xpath