position Function
Returns the position, or index number, of the node, relative to all the selected nodes in the node list.
number position()
Remarks
The position of the node is is 1-based, so the first node returns a position of 1.
Example
The following code example illustrates the effects of the position()
function.
XML File (position.xml)
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="position.xsl"?> <test> <x a="a11"> <x a="a21"> <x a="a31"> <y b="b31">y31</y> <y b="b32">y32</y> </x> </x> </x> <x a="a12"> <x a="a22"> <y b="b21">y21</y> <y b="b22">y22</y> </x> </x> <x a="a13"> <y b="b11">y11</y> <y b="b12">y12</y> </x> <x a="a14"> <y b="b01">y01</y> <y b="b02">y02</y> </x> </test>
XSLT File (position.xsl)
<?xml version='1.0'?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" omit-xml-declaration="yes"/> <xsl:template match="/"> <xsl:apply-templates select="//x"/> </xsl:template> <xsl:template match="*"> <xsl:element name="{name()}"> <xsl:apply-templates select="@*"/> <xsl:value-of select="position()"/> </xsl:element>\n </xsl:template> <xsl:template match="@*"> <xsl:attribute name="{name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:template> </xsl:stylesheet>
Output
The above XSLT style sheet, when applied to the source XML file, maps all the <x>
elements to new <x>
elements whose content holds their position in the document order.
<x a="a11">1</x> <x a="a21">2</x> <x a="a31">3</x> <x a="a12">4</x> <x a="a22">5</x> <x a="a13">6</x> <x a="a14">7</x>
To illustrate the sensitivity of the position()
function to the context from which it is operated, let's replace the following template rule (from the XSLT file above):
<xsl:template match="/"> <xsl:apply-templates select="//x"/> </xsl:template>
with this one:
<xsl:template match="/"> <xsl:apply-templates select="//x[1]"/> </xsl:template>
The result is as follows:
<x a="a11">1</x> <x a="a21">2</x> <x a="a31">3</x> <x a="a22">4</x>
On the other hand, if we replace the template rule with the following one:
<xsl:template match="/"> <xsl:apply-templates select="//x[2]"/> </xsl:template>
we get the following result:
<x a="a12">1</x>
See Also
Data Types in Schemas | XDR Schema Data Types Reference | XML Data Types Reference