XSLT <xsl:key>
Element
The <xsl:key>
element specifies a name-value pair assigned to a specific element in an XML document. This key is used with the key()
function in XPath expressions to access assigned elements in an XML document.
<xsl:key>
Element
Syntax
The syntax of <xsl:key>
is as follows:
<xsl:key
name=QName
match=Pattern
use=Expression >
</xsl:key>
Attributes
The table describes the meaning of the attributes of <xsl:key>
:
Name | Description |
---|---|
name | Name of the key to be used. |
match | Patterns used to identify a node that holds this key. |
use | XPath expression to identify the value of the nodes of xml document. |
Example
Let's see an example:
books.xml
<?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.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="author-search" match="book" use="author"/>
<xsl:template match="/">
<html>
<body>
<h2>The Bookstore</h2>
<table border="1">
<tr bgcolor="#6565d5">
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Price</th>
</tr>
<xsl:for-each select="key('author-search', 'Tom Nolan')">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="year"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
note
In the example, the <xsl:key>
element is used to print the book details of all books with author "Tom Nolan".