XSLT » Functions » key

Syntax:
node-set = key(name, value)
value
The mandatory value attribute specifies the value of the key. This value is type dependent. The value can be of type node-set. For all other types, the value will be converted to a string by the XPath string core function.
name
The mandatory name attribute specifies the qname of the key. The value of the name attribute of the key function must match the value of the name attribute of one or more corresponding xsl:key elements. (This is possible since a key does not have to be unique and, further, a key can refer to more than one node and a node can have more than one key.)

The key function returns a node-set that contains all of the nodes in an XML document that match the name-value pair of the name and value arguments. This function is primarily used for locating nodes in very large XML documents. Since there may not be a match, the returned node-set can contain zero or more nodes. (The actual efficiency of finding the nodes is implementation dependent and is typically based upon prior indexing.)

The key function is used in conjunction with the xsl:key element. Before the key function can be called, there must have been a prior declaration of an xsl:key element that has a name attribute that matches the name argument of the key function.
 
The xsl:key element alerts the XSLT processor to create an indexed data structure based upon the key expressions ahead of time. If there are no xsl:key elements, then the time-consuming indexing is not performed.
 
The xsl:key element declares a named key that can be used by the key function.

Examples

Code:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:key name="stafflist" match="programmer" use="@name" />
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="key('stafflist', 'Road Runner')">
<div>
NAME: <xsl:value-of select="@name" />
<br />
DOB: <xsl:value-of select="@dob" />
<br />
AGE: <xsl:value-of select="@age" />
<br />
ADDRESS: <xsl:value-of select="@address" />
<br />
PHONE: <xsl:value-of select="@phone" />
<hr />
</div>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Output:
NAME: Road Runner
DOB: 01/19/1953
AGE: 48
ADDRESS: 135 Desert View Street
PHONE: 865-555-5555
Explanation:

In this example, we search for Road Runner. This is the code for xslt_example_key.xsl.
 
We use the DevGuru Staff List XML file for our example with the following header:
<?xml-stylesheet type="text/xsl" href="xslt_example_key"?>

Language(s): XSLT

See Also: