Keys give you an easy way to identify elements, and you can match specific keys with the pattern "key()" . Chapter 9 discusses how to use keys in detail, but Ill include a quick example here.
You use the <xsl:key> element to create a key. This element is a top-level element, so it appears outside templates and as a child element of <xsl:stylesheet> . In the following example, I use a key to match planets whose COLOR attribute is set to BLUE, which means Earth:
<?xml version="1.0"?> <?xml-stylesheet type="text/xml" href="planets.xsl"?> <PLANETS> . . . <PLANET COLOR="BLUE"> <NAME>Earth</NAME> <MASS UNITS="(Earth = 1)">1</MASS> <DAY UNITS="days">1</DAY> <RADIUS UNITS="miles">2107</RADIUS> <DENSITY UNITS="(Earth = 1)">1</DENSITY> <DISTANCE UNITS="million miles">128.4</DISTANCE><!--At perihelion--> </PLANET> </PLANETS>
Now I can create a key named COLOR that matches <PLANET> elements by checking their COLOR attribute:
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:key name="COLOR" match="PLANET" use="@COLOR"/> . . .
Now I can use the pattern "key()" to match <PLANET> elements with the COLOR attribute set to BLUE as follows :
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:key name="COLOR" match="PLANET" use="@COLOR"/> <xsl:template match="/PLANETS"> <HTML> <HEAD> <TITLE> The Planets Table </TITLE> </HEAD> <BODY> <H1> The Planets Table </H1> <TABLE BORDER="2"> <TR> <TD>Name</TD> <TD>Mass</TD> <TD>Radius</TD> <TD>Day</TD> </TR> <xsl:apply-templates select="key('COLOR', 'BLUE')"/> </TABLE> </BODY> </HTML> </xsl:template> . . .
And heres the resultas you can see, Earth was the only planet that matched the pattern I used:
<HTML> <HEAD> <TITLE> The Planets Table </TITLE> </HEAD> <BODY> <H1> The Planets Table </H1> <TABLE BORDER="2"> <TR> <TD>Name</TD> <TD>Mass</TD> <TD>Radius</TD> <TD>Day</TD> </TR> <TR> <TD>Earth</TD> <TD>1 (Earth = 1)</TD> <TD>2107 miles</TD> <TD>1 days</TD> </TR> </TABLE> </BODY> </HTML>