Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

XSLT <xsl:key> elements


May 28, 2021 XSL T


Table of contents


XSLT and lt;xsl: key.gt; elements

The XSLT-lt;xsl:key-gt; element is used to declare a key that is used by the key() function.


XSLT <xsl:key> elements Complete XSLT element reference manual

Definitions and usages

The element is a top-level element that declares a named key (that is, the name and value pair assigned to the element specified in the XML document). The key is used in style sheets by the key() function to help you effectively access assigned elements in complex XML documents.

Note: Keys don't have to be unique!


Grammar

<xsl:key
name="name"
match="pattern"
use="expression"/>

Property

Attributes value describe
name name Required.The name of the specified key.
match pattern Required.Define which node is applied to.
use expression Required.Specifies the expression that is used as the value of the keys to each node.

Instance 1

Suppose you have an XML file .xml "persons":

<persons>
<person name="Tarzan" id="050676"/>
<person name="Donald" id="070754"/>
<person name="Dolly" id="231256"/>
</persons>

You can define a key in the XSL file as follows:

<xsl:key name="preg" match="person" use="@id"/>

To find the person with id "050676", use these codes (in the XSL file):

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:key name="preg" match="person" use="@id"/>

<xsl:template match="/">
<html>
<body>
<xsl:for-each select="key('preg','050676')">
<p>
Id: <xsl:value-of select="@id"/><br />
Name: <xsl:value-of select="@name"/>
</p>
</xsl:for-each>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

XSLT <xsl:key> elements Complete XSLT element reference manual

Related tutorials

XML tutorial