Key Basics

Contact Us or call 1-877-932-8228
Key Basics

Key Basics

XSLT keys provide a simple and efficient way of looking up values based on other values. First, we will take a look at the syntax of keys and then we will look at how they are used in practice.

<xsl:key/>

Keys are created with the <xsl:key> tag, which must be a child of <xsl:stylesheet/>. It has three required attributes shown in the table below.

xsl:key Attributes
Attribute Description
name Name of the key.
match Pattern to match.
use The part of the matched node that will serve as the look-up index.

The key() Function

The key() function is used to look up the node or nodes specified by the key. It takes two arguments: the name of the key and the index.

The example below shows how to create a key and then look up a value in the key.

Code Sample:

Keys/Demos/SimpleKey.xml
<?xml version="1.0"?>
<?xml-stylesheet href="SimpleKey.xsl" type="text/xsl"?>
<beatles>
	<beatle link="http://www.paulmccartney.com">
		<name>
			<firstname>Paul</firstname>
			<lastname>McCartney</lastname>
		</name>
		<role>Singer</role>
	</beatle>
	<beatle link="http://www.johnlennon.com">
		<name>
			<firstname>John</firstname>
			<lastname>Lennon</lastname>
		</name>
		<role>Singer</role>
	</beatle>
	<beatle link="http://www.georgeharrison.com">
		<name>
			<firstname>George</firstname>
			<lastname>Harrison</lastname>
		</name>
		<role>Guitarist</role>
	</beatle>
	<beatle link="http://www.ringostarr.com">
		<name>
			<firstname>Ringo</firstname>
			<lastname>Starr</lastname>
		</name>
		<role>Drummer</role>
	</beatle>
</beatles>

Code Sample:

Keys/Demos/SimpleKey.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
				xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="xml" indent="yes"/>
	<xsl:key name="keyBeatle" match="beatle" use="name/firstname"/>
	<xsl:param name="FirstName" select="'John'"/>
	
	<xsl:template match="/">
		<Match>
			<xsl:value-of select="key('keyBeatle',$FirstName)/@link"/>
		</Match>
	</xsl:template>
	
</xsl:stylesheet>

In the example above, the key is created with this line:

<xsl:key name="keyBeatle" match="beatle" use="name/firstname"/>

Imagine that it creates a lookup table that looks something like this:

Index Node-set
Paul Paul McCartney beatle node
John John Lennon beatle node
George George beatle node
Ringo Ringo beatle node

The key() function is used to look up the node or nodes specified by the key. It takes two arguments: the name of the key and the index.

<xsl:value-of select="key('keyBeatle',$FirstName)/@link"/>

As $Firstname is set to 'John' in the xsl:param, this line above returns "http://www.johnlennon.com". As you can see, the key() function returns nodes in the XML document. We can use XPath to drill down further into these nodes. In the example above, we drill down to the link attribute of the beatle node returned by key().

Next