Using the key() Function

MSXML 5.0 SDK

Microsoft XML Core Services (MSXML) 5.0 for Microsoft Office - XSLT Developer's Guide

Using the key() Function

The other side of the <xsl:key> element is provided by the built-in XSLT key() function. The purpose of this function is to retrieve the node or nodes keyed to a particular name and value.

The syntax of the key() function is as follows:

key(name, value)

The key() function returns a node-set containing all nodes which match the key identified by the arguments. The following arguments are passed to it.

  • name: A string providing the name of the key to use. It corresponds to the name of one or more keys defined by <xsl:key> elements.
  • value: The value of the desired key. Technically, this argument can be of any data type. However, if it is a node-set, the function will return all nodes with the same value. Note that this argument can be a variable reference.

If the value of name does not match the name of a key defined by a corresponding <xsl:key> element, the key() function will return an empty node-set.

The following table shows some brief examples of the node-sets returned by calls to the key() function:

Key declaration key() function call Returns
<xsl:key name="isbn_key" match="book" use="@isbn"/> key("isbn_key", "991100-102") The <book> element that corresponds to the title Quantum Superstring Electrodynamics for Newbies
<xsl:key name="categ_key" match="book" use="category"/> key("categ_key", "Fiction") The <book> element that corresponds to Jambing on the Trixels
<xsl:key name="categ_key" match="book" use="category"/> key("categ_key", "Non-fiction") Every <book> element, except the one that corresponds to Jambing on the Trixels
<xsl:key name="author_id" match="book" use="author"/> key("author_id", contains("Culbert")) The two <book> elements that correspond to Fretting Over Your Guitar and Quantum Superstring Electrodynamics for Newbies

Files Used for This Topic