Reputation: 163
I want to get the position of an element in XSLT.
Input:
<parent_root>
<root>
<ele>
<fig/>
</ele>
<got/>
<ele>
<fig/>
</ele>
<got/>
<got/>
<ele>
<fig/>
</ele>
<got/>
</root>
</parent_root>
Output should be:
fig_1
fig_2
fig_3
fig_4
Tried code:
<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>
The error I am getting:
A sequence of more than one item is not allowed as the third argument of concat() (1, 2, ...)
How can I solve this? I am using XSLT 2.0. Thank you
Upvotes: 1
Views: 603
Reputation: 29022
The position()
function is relative to the current template, so it will always return 1
in your case. But you can easily achieve a similar function by counting the preceding <root>
ancestor elements of your current <fig>
element:
<xsl:template match="fig">
<xsl:value-of select="concat('fig_',count(ancestor::root/preceding-sibling::root)+1,'
')" />
</xsl:template>
The last part of the concat()
function, '
'
, is just there to provide the well formatted output of
fig_1
fig_2
fig_3
EDIT, because the question was changed:
To get all <got>
elements and count all of its preceding <got>
elements, you can use the following template:
<xsl:template match="got">
<xsl:value-of select="concat('fig_',count(preceding::got)+1,'
')" />
</xsl:template>
Its output, which matches all <got>
elements, is:
fig_1
fig_2
fig_3
fig_4
If you would match the <fig>
elements, you would only get three nodes as output instead.
Upvotes: 2