Search code examples
xmldomxpathxml-parsingdomxpath

Get XPath Position Predicates from Nodes


Is there a way, to get the XPath positional predicates from a certain instance of a node?

So I search for a position(Node) function, which returns the position of a node in a DOM tree.

Example: page.xml

<page>
    <line>
        <wd> bla </wd>
        <wd> blabla </wd>
    </line>
    <line>
        <wd> lorem </wd>
        <wd> ipsum </wd>
        <wd> dolor </wd>
        <wd> sit </wd>
    </line>
</page>

So the function applied on the node with the content ipsum should return something like: second word, second line, first page.

cheers


Solution

  • You can get the position of a node using the preceding-sibling axis. For example, if the wd element containing the string 'ipsum' is in variable $ipsum, you can the position within its parent element with:

    count($ipsum/preceding-sibling::*) + 1
    

    And the position of the parent of $ipsum with:

    count($ipsum/../preceding-sibling::*) + 1