position 函数 (XPath)

返回节点相对与节点列表中所有选定节点的位置(或索引号)。

number position()

备注

节点位置从 1 开始,所以第一个节点返回位置 1。

示例

以下代码示例阐释 position() 函数的效果。

XML 文件 (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 文件 (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>

ms256233.collapse_all(zh-cn,VS.120).gif输出

如将上面的 XSLT 样式表应用于 XML 源文件,该表会将所有 <x> 元素映射到按文档顺序保存内容的新 <x> 元素。

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

为说明 position() 函数在操作上下文中的敏感度,我们将(从上面的 XSLT 文件中)替换以下模板规则:

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

替换为:

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

结果如下所示:

<x a="a11">1</x>
<x a="a21">2</x>
<x a="a31">3</x>
<x a="a22">4</x>

另一方面,如果我们用以下规则替换上述模板规则:

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

将得到以下结果:

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

请参见

参考

XML 数据类型引用