关于xml:获取元素在XSLT中的位置

Getting the position of an element in XSLT

我想获取元素在XSLT中的位置。

输入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<parent_root>
  <root>
    <ele>
      <fig/>
    </ele>
    <got/>
    <ele>
      <fig/>
    </ele>
    <got/>
    <got/>
    <ele>
      <fig/>
    </ele>
    <got/>
  </root>
</parent_root>

输出应为:

1
2
3
4
fig_1
fig_2
fig_3
fig_4

尝试代码:

1
2
3
4
5
6
<xsl:template match="fig">
  <xsl:when test="parent::ele/following-sibling::got">
    <xsl:variable name="ID2" select="parent::ele/following-sibling::got/position()"/>
    <xsl:value-of select="concat('fig_','$ID2')"/>
  </xsl:when>
</xsl:template>

我得到的错误:

A sequence of more than one item is not allowed as the third argument of concat() (1, 2, ...)

我该如何解决?我正在使用XSLT 2.0。谢谢


position()函数是相对于当前模板的,因此在您的情况下,它将始终返回1。但是,您可以通过计算当前<fig>元素的前面的<root>祖先元素来轻松实现类似的功能:

1
2
3
<xsl:template match="fig">
    <xsl:value-of select="concat('fig_',count(ancestor::root/preceding-sibling::root)+1,' ')" />
</xsl:template>

concat()函数的最后一部分' '就位于此处,用于提供

格式正确的输出

1
2
3
fig_1
fig_2
fig_3

EDIT,因为问题已更改:
要获取所有<got>元素并计算其所有先前的<got>元素,可以使用以下模板:

1
2
3
<xsl:template match="got">
    <xsl:value-of select="concat('fig_',count(preceding::got)+1,' ')" />
</xsl:template>

与所有<got>元素匹配的输出为:

1
2
3
4
fig_1
fig_2
fig_3
fig_4

如果匹配<fig>元素,则只能得到三个节点作为输出。