Skip to content

XSLT key() Function

How to use the XSLT key() function to efficiently retrieve node-sets from an XML document by matching values defined in <xsl:key> elements.

XSLT generate-id() Function

The key function returns a node-set from the document, using the index specified by an <xsl:key> element.

Syntax

node-set key(string, object)

Input Parameters

Parameter Required/Optional Description
string Required Specifies the name of an xsl:key element
object Required A string to search for

Example

Consider the following example about a bookstore:

books.xmlxml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>

<bookstore>
	<book category="children">
		<title lang="en">Harry Potter</title>
		<author>J K. Rowling</author>
		<year>2005</year>
		<price>29.99</price>
	</book>
	<book category="web">
		<title lang="en">XQuery Tips</title>
		<author>Tom Nolan</author>
		<year>2022</year>
		<price>39.99</price>
	</book>
	<book category="web">
		<title lang="en">Learn XML</title>
		<author>Tutorial Reference</author>
		<year>2022</year>
		<price>9.99</price>
	</book>
</bookstore>
books.xslxml
<?xml version="1.0"  encoding="UTF-8"?>  
<xsl:stylesheet version="1.0"  
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  
  
<xsl:key name="booklist" match="book" use="title"  />  
  
<xsl:template match="/">  
	<html>  
		<body>  
			<xsl:for-each select="key('booklist', 'Harry Potter')">  
				<p>  
				Title: <xsl:value-of select="title"  />  
				<br />  
				Author: <xsl:value-of select="author"  />  
				<br />  
				Price: <xsl:value-of select="price"  />  
				</p>  
			</xsl:for-each>  
		</body>  
	</html>  
</xsl:template>  
  
</xsl:stylesheet>

And the output is:

<html>  
	<body>  
		<p> Title: Harry Potter<br/>
		Author: J K. Rowling<br/>
		Price: 29.99</p>  
	</body>  
</html>
Navigation