XSLT <xsl:key>
❮ Complete XSLT Element Reference
定義和用法
<xsl:key> 元素是一個頂層元素,用於宣告一個命名的鍵,該鍵可以在樣式表中使用 key() 函式。
注意: 鍵不一定是唯一的!
語法
<xsl:key
name="name"
match="pattern"
use="expression"/>
屬性
Attribute | 值 | 描述 |
---|---|---|
name | name | 必需。指定鍵的名稱 |
match | pattern | 必需。定義鍵將應用於哪些節點 |
use | expression | 必需。每個節點對應的鍵的值 |
示例 1
假設你有一個名為 "persons.xml" 的 XML 檔案
<persons>
<person name="Tarzan" id="050676"/>
<person name="Donald" id="070754"/>
<person name="Dolly" id="231256"/>
</persons>
你可以在 XSL 檔案中像這樣定義一個鍵
<xsl:key name="preg" match="person" use="@id"/>
要找到 id="050676" 的 person,(在 XSL 檔案中)編寫
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="preg" match="person" use="@id"/>
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="key('preg','050676')">
<p>
Id: <xsl:value-of select="@id"/><br />
Name: <xsl:value-of select="@name"/>
</p>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
❮ Complete XSLT Element Reference