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.
<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>
NAME: Road Runner
DOB: 01/19/1953
AGE: 48
ADDRESS: 135 Desert View Street
PHONE: 865-555-5555
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"?>