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>
輸出
上述 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>