key function
xsl:stylesheet
ELEMENT: xsl:key
<xsl:key
match="pattern"
name="qname"
use="expression"
>
</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.
match="pattern"
The mandatory
match
attribute defines the nodes to which the key will be applied.
name="qname"
The mandatory
name
attribute is a qname that identifies the key. A qname is a qualified name that is composed of an optional namespace prefix, a colon, which is only present if there is a prefix, and a mandatory XML name (for example, xsl:zipcode or zipcode).
use="expression"
The mandatory
use
attribute is an expression or string that is used to determine the value of the key for each node.
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"?>
and we name it: xslt_example_key.xml
We search for Road Runner.
Code for xslt_example_key.xsl:
<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:
Click to view output in separate window
- requires Internet Explorer
Copyright 1999-2001 by Infinite Software Solutions, Inc. All rights reserved.
Trademark Information