key_1-input.xml
<?xml version="1.0"?>
<products>
<product
id="p1" name="Delta" price="3250" stock="4" country="Denmark"/>
<product
id="p2" name="Golf" price="1000" stock="5" country="Germany"/>
<product
id="p3" name="Alpha" price="1200" stock="19" country="Germany"/>
<product
id="p4" name="Foxtrot" price="1500" stock="5" country="Australia"/>
<product
id="p5" name="Tango" price="1225" stock="3" country="Japan"/>
</products>
key_1-stylesheet.xsl
<?xml version="1.0"?>
<xsl:stylesheet
version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output
indent="yes" omit-xml-declaration="yes"/>
<xsl:key
name="myKey" match="products/product" use="@id"/>
<xsl:variable
name="x" select="'p4'"/>
<xsl:template
match="/">
<products>
<product
id="{$x}">
<navn>
<xsl:value-of
select="key('myKey', $x)/@name"/>
</navn>
<country>
<xsl:value-of
select="key('myKey', $x)/@country"/>
</country>
</product>
</products>
</xsl:template>
</xsl:stylesheet>
key_1-output
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product
id="p4">
<navn>Foxtrot</navn>
<country>Australia</country>
</product>
</products>
The element xsl:key works hand in hand with the key() function. If the input file is huge and you have many look-ups, xsl:key can speed up the process many times.
Updated 2009-03-19