<xsl:key> |
Defines an index against the current document. The element is defined with three attributes: a name, which names this index; a match, an XPath expression that describes the nodes to be indexed; and a use attribute, an XPath expression that defines the property used to create the index.
Category
Top-level element
Required Attributes

name
  Defines a name for this key.

match
  Represents an XPath expression that defines the nodes to be indexed by this key.

use
  Represents an XPath expression that defines the property of the indexed nodes that will be used to retrieve nodes from the index.

Optional Attributes
None.
Content
None. <xsl:key> is an empty element.
Appears in
<xsl:key> is a top-level element and can only appear as a child of <xsl:stylesheet>.
Defined in
XSLT section 12.2, Keys.
Example
Here is a stylesheet that defines two <xsl:key> relations against an XML document:
    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>
    <xsl:strip-space elements="*"/>

      <xsl:key name="language-index" match="defn" use="@language"/>
      <xsl:key name="term-ids"       match="term" use="@id"/>

      <xsl:param name="targetLanguage"/>

      <xsl:template match="/">
        <xsl:apply-templates select="glossary"/>
      </xsl:template>

      <xsl:template match="glossary">
        <html>
          <head>
            <title>
              <xsl:text>Glossary Listing: </xsl:text>
              <xsl:value-of select="key('language-index',
            $targetLanguage)[1]/preceding-sibling::term"/>
              <xsl:text> - </xsl:text>
              <xsl:value-of select="key('language-index',
            $targetLanguage)[last()]/preceding-sibling::term"/>
            </title>
          </head>
          <body>
            <h1>
              <xsl:text>Glossary Listing: </xsl:text>
              <xsl:value-of select="key('language-index',
            $targetLanguage)[1]/ancestor::glentry/term"/>
              <xsl:text> - </xsl:text>
              <xsl:value-of select="key('language-index',
            $targetLanguage)[last()]/ancestor::glentry/term"/>
            </h1>
            <xsl:for-each select="key('language-index', $targetLanguage)">
              <xsl:apply-templates select="ancestor::glentry"/>
            </xsl:for-each>
          </body>
        </html>
      </xsl:template>

      ...

    </xsl:stylesheet>
For a complete discussion of this stylesheet, illustrating how the <xsl:key> relations are used, see Section 5.2.3 in Chapter 5.