XSLT » Elements » xsl:key


The xsl:key element is used to declare a named key that can be used by the key function in expressions and patterns. The key function has two arguments: the key name and the value (consider this to be a key-value pair). The appropriate use of these key-value pairs can permit easy access to information in complex XML documents.

A key does not have to be unique. Further, a key can refer to more than one node and a node can have more than one key.
There is no limit to the number of the xsl:key elements that can occur. However, each xsl:key element can only be a child of the xsl:stylesheet or the xsl:transform elements. It cannot contain any elements as content, nor can it appear inside a template.
The xsl:key element alerts the XSLT processor to create an indexed data structure for the key expressions ahead of time. This indexed data structure will be used by the key function. If there are no xsl:key elements, then the time-consuming indexing is not performed.
This is not a self-closing element. The separate closing element is mandatory.


<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="/">
<xsl:for-each select="key('stafflist', 'Road Runner')">
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 />
NAME: Road Runner
DOB: 01/19/1953
AGE: 48
ADDRESS: 135 Desert View Street
PHONE: 865-555-5555

Here, 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.xsl"?>

Language(s): XSLT

See Also: