XSLT - What is <xsl:key>?
What is <xsl:key>
?
-
<xsl:key>
is used to define an index (like a lookup table) in XSLT. -
Instead of searching the entire XML repeatedly with XPath, you can define a key and then access nodes quickly with the
key()
function. -
It’s mainly used for grouping and fast lookups.
Syntax
<xsl:key name="keyName" match="pattern" use="expression"/>
-
name
→ the name of the key (used when callingkey()
). -
match
→ XPath pattern that selects the nodes to index. -
use
→ expression that defines the value(s) of the key (what you’ll look up with).
Example XML
<library>
<book>
<title>XML Basics</title>
<author>Alice</author>
</book>
<book>
<title>XSLT in Action</title>
<author>Bob</author>
</book>
<book>
<title>Advanced XML</title>
<author>Alice</author>
</book>
</library>
Defining a Key
We want to index books by author.
<xsl:key name="booksByAuthor" match="book" use="author"/>
-
This says:
“For each<book>
, create an index entry where the key is the author’s name and the value is the<book>
node.”
Using the Key
<xsl:template match="/">
<html>
<body>
<h2>Books by Alice</h2>
<ul>
<!-- Lookup all books where author = 'Alice' -->
<xsl:for-each select="key('booksByAuthor', 'Alice')">
<li><xsl:value-of select="title"/></li>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
Output
<html>
<body>
<h2>Books by Alice</h2>
<ul>
<li>XML Basics</li>
<li>Advanced XML</li>
</ul>
</body>
</html>
Why use <xsl:key>
?
-
Performance → instead of scanning the whole document every time,
key()
gives fast access. -
Grouping → often used with
generate-id()
andkey()
to group elements by some property (like grouping books by author). -
Reusability → once defined, you can use the key multiple times in your XSLT.