XPath 1.0: Finding count of nodes before a specifi

2019-07-21 22:21发布

问题:

I am familiar with using preceding axes in XSLT for finding determining the number of preceding elements given the current context. However, I don't see a way to do the same given a node that I've stored in a variable. For example:

<xsl:variable name="matchedBook" select="book[text()='The Hobbit']"/>
<xsl:variable name="precedingBookCount" select="count(???)"/>

Given the following XML, precedingBookCount should equal 3.

<available>
    <book>Lord of the Rings</book>
    <book>The Hunger Games</book>
</available>
<purchased>
    <book>Ready Player One</book>
    <book>The Hobbit</book>
    <book>Lord of the Flies</book>
</purchased>

I see in XPath 2.0 that there is a NodeComp operator << that I could use, but this does not appear to be present in XPath 1.0.

How can I go about doing this in XPath 1.0 then?

回答1:

<xsl:variable name="precedingBookCount" select="count($matchedBook/preceding-sibling::book | $matchedBook/preceding::book)"/> should do.

Actually it suffices to do <xsl:variable name="precedingBookCount" select="count($matchedBook/preceding::book)"/>.