XSLT <xsl:key>Element


XSLT 元素参考手册Complete XSLT Element Reference

Definition and Usage

The <xsl:key> element is a top-level element that can declare a named key (i.e., assign names and value pairs to specified elements in an XML document). This key is used in style sheets through the key() function, helping you efficiently access assigned elements in complex XML documents.

Note:Keys do not have to be unique!


Syntax

<xsl:key
name="name"
match="pattern"
use="expression"/>

Attributes

Attribute Value Description
name name Required. Specifies the name of the key.
match pattern Required. Defines which node the key is applied to.
use expression Required. Specifies the expression to use as the key value for each node.

Example 1

Suppose you have an XML file named "persons.xml":

<persons>
<person name="Tarzan" id="050676"/>
<person name="Donald" id="070754"/>
<person name="Dolly" id="231256"/>
</persons>

You can define a key in the XSL file as follows:

<xsl:key name="preg" match="person" use="@id"/>

To find the person with id="050676", use this code (in the XSL file):

<?xml version="1.0" encoding="ISO-8859-1"?>
<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>


XSLT 元素参考手册Complete XSLT Element Reference Other Extensions