0

如何在 Xpath 1.0 中获取当前节点位置?

我正在尝试/position(),但它不起作用。我也试过了/@position()

4

2 回答 2

3

这取决于您所说的“位置”的含义-该position()函数不一定与节点在其所属的 XML 树中的位置有任何关系,它仅表示当前上下文节点在“当前节点列表”中的位置(以及其含义取决于评估 XPath 的宿主语言,例如在 XSLT 中,它表示节点列表 -select由最近的apply-templatesor for-each)。

如果您有一个名为的元素foo,并且您想知道它是foo其父元素中的第一个、第二个等(即您需要将其返回为 的数字 N ../foo[N]),那么您可以通过计算其前面的兄弟姐妹来做到这一点同名

count(preceding-sibling::foo) + 1

但是,为此,您需要在构建 XPath 表达式时预先知道名称 - 纯 XPath 1.0 不允许您计算“与当前节点同名的先前兄弟姐妹”的数量。

一些宿主语言可能会提供一个允许这样做的变量或函数 - 再次以 XSLT 作为示例,您可以使用该current()函数从表达式中的任何位置引用当前上下文节点,包括内部谓词。在 XPath 2.0 中,您可以使用

for $cur in . return (count(preceding-sibling::*[name() = name($cur)]) + 1)
于 2014-08-29T13:53:23.863 回答
0
<xsl:template name="node-index-of">
    <xsl:param name="nodes" />
    <xsl:param name="node" />
    <xsl:param name="index" />
    <xsl:choose>
        <xsl:when test="$nodes[position()=$index]=$node">
            <xsl:value-of select="$index"/>    
        </xsl:when>
        <xsl:when test="$index=count($nodes)">
            <xsl:value-of select="$index"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:call-template name="node-index-of">
                <xsl:with-param name="nodes" select="$nodes" />
                <xsl:with-param name="node" select="$node" />
                <xsl:with-param name="index">
                    <xsl:value-of select="$index+1"/>
                </xsl:with-param>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

$index 从 1 开始

于 2016-04-03T23:23:45.517 回答