XPath 1.0: Finding count of nodes before a specified node

馋奶兔 提交于 2019-12-11 03:35:27

问题


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)"/>.



来源:https://stackoverflow.com/questions/11037979/xpath-1-0-finding-count-of-nodes-before-a-specified-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!