This is wrong:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="elm">
<xsl:value-of select="concat(position(), ' ', @val)"/>
</xsl:template>
</xsl:stylesheet>
When run with many XSLT processors this will produce the following (unwanted) output:
2 data1
4 data2
6 data3
8 data4
10 data5
12 data6
14 data7
The reason is that when templates are applied to the children of the top element, this includes the children that are white-space-only text nodes -- between every two consecutive elm
elements.
So, Oded's solution is wrong.
Here is one correct solution (and one of the shortest possible):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="elm">
<xsl:value-of select="concat(position(), ' ', @val, '
')"/>
</xsl:template>
</xsl:stylesheet>
This transformation produces the correct result:
1 data1
2 data2
3 data3
4 data4
5 data5
6 data6
7 data7
Do note:
The use of the <xsl:strip-space elements="*"/>
to direct the XSLT processor to discard any white-space-only text nodes.
The use of the XPath concat()
function to glue together the position, the data and the NL character.