Share via

position Function

Returns the position, or index number, of the node, relative to all the selected nodes in the node list.

      number position()


The position of the node is is 1-based, so the first node returns a position of 1.


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"?>      
    <x a="a11">
      <x a="a21">
        <x a="a31">
          <y b="b31">y31</y>
          <y b="b32">y32</y>
    <x a="a12">
      <x a="a22">
        <y b="b21">y21</y>
        <y b="b22">y22</y>
    <x a="a13">
      <y b="b11">y11</y>
      <y b="b12">y12</y>
    <x a="a14">
      <y b="b01">y01</y>
      <y b="b02">y02</y>

XSLT File (position.xsl)

<?xml version='1.0'?>

  <xsl:output method="xml"   

  <xsl:template match="/">
     <xsl:apply-templates select="//x"/>

  <xsl:template match="*">
    <xsl:element name="{name()}">
        <xsl:apply-templates select="@*"/>
        <xsl:value-of select="position()"/>

  <xsl:template match="@*">
     <xsl:attribute name="{name()}">
        <xsl:value-of select="."/>



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"/>

with this one:

<xsl:template match="/">
     <xsl:apply-templates select="//x[1]"/>

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]"/>

we get the following result:

<x a="a12">1</x>                 

See Also


XML Data Types Reference