Matching by Key

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 I’ll 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> ...

Get Inside XSLT now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.