xsl:key Element

The <xsl:key> element declares a named key for use with the key function in XML Path Language (XPath) expressions for enabling easier access into complex XML documents. Keys are top-level elements, which means they cannot appear within a template.

<xsl:key
  name = QName
  match = Pattern
  use = expression>
</xsl:key>

Attributes

  • name
    Identifies the key within the XSL Transformations (XSLT) document.
  • match
    Specifies the pattern that should be matched. The Extensible Stylesheet Language (XSL) processor effectively preprocesses the source document and identifies all elements within the document that match the given pattern. Because the match is done on a node-by-node basis, it is not necessary to specify global pattern matches in the pattern string.
  • use
    Provides the value to reference an element that satisfies the pattern specified in the match attribute. Because the context is temporarily set to that element, the value of the use attribute should be an XPath expression that identifies each particular match, such as an id or similar element.

Element Information

Number of occurrences Unlimited
Parent elements xsl:stylesheet
Child elements None

Remarks

The <xsl:key> element provides an alternative mechanism for addressing elements within an XML document. In effect, keys create a directory of specific elements from an XML source document, with the values generated from the use expressions referring to those elements. The primary difference between a key and an id is that an id must be a fixed qualified name, while a key can be created from either one or several concatenated expressions.

The <xsl:key> element is designed to be used with the XPath key function. The key function takes two arguments — the name of the key and its value — and then either retrieves the node or nodes associated with that key–value pair, or returns an empty node-set if no matching element is found. Unlike id elements, a key() expression may be matched by more than one node.

It is possible, of course, to create an XPath expression that retrieves the same data a key would, but when working with relatively large XML documents, a key is often faster because it essentially indexes the locations of the desired data ahead of time.

While the XSLT parser compiles the search expressions for the key element ahead of time, the current implementation does not explicitly create the index unless a key function is encountered. This guarantees that if a transformation bypasses the key function call then the initial time-intensive indexing is not performed. Note also that, in accordance with the Worldwide Web Consortium (W3C) specifications, parameter or variable references cannot be used as part of a <xsl:key> match, ostensibly to avoid circular references.

See Also

XSLT Elements | key Function | id Function

 Last updated on Saturday, April 10, 2004

© 1992-2003 Microsoft Corporation. All rights reserved.