Skip to content

xsl:key

Declares a named index for fast lookup with the XPath key() function.

<xsl:key name="emp-by-dept" match="employee" use="@department"/>

For each node in the source document that matches match, the index stores it under the key value(s) computed by use. A subsequent key('emp-by-dept', 'Sales') returns all employees in the Sales department in O(1) plus result size, instead of O(n) per lookup.

Multiple xsl:key declarations with the same name are merged into a single index. With composite="yes", the use expression must produce a sequence and the entire sequence is treated as a composite key.

Attributes

Attribute Description
name Key name (QName). Required.
match Pattern selecting the nodes to index. Required.
use XPath expression producing the key value(s). Required.
composite yes to treat the use sequence as a composite key.

Example

Looking up employees by department:

<xsl:key name="emp-by-dept" match="employee" use="@department"/>

<xsl:template match="/">
  <xsl:for-each select="distinct-values(//employee/@department)">
    <dept name="{.}">
      <xsl:for-each select="key('emp-by-dept', .)">
        <emp><xsl:value-of select="@name"/></emp>
      </xsl:for-each>
    </dept>
  </xsl:for-each>
</xsl:template>