In this section, we’ll look at using
<xsl:key> to group items in an XML
document. This approach is commonly referred to as the “Muench
method,” after Oracle XML Evangelist (and O’Reilly
author) Steve Muench, who first suggested this technique. The Muench
method has three steps:
key for the
property we want to use for grouping.
Select all of the nodes we want to group. We’ll do some
tricks with the
generate-id() functions to
find the unique grouping values.
For each unique grouping value, use the
key() function to retrieve all nodes that match it. We can further
sort those nodes if we want.
Well, that’s how the technique works—let’s start building the stylesheet that makes the magic happen. The first step, creating a key function, is easy. Here’s how it looks:
<xsl:key name="zipcodes" match="address" use="zip"/>
defines a new index called
zipcodes. It indexes
<address> elements based on the value
<zip> element they
Now that we’ve defined our
key, we’re ready for the complicated part.
We use the
generate-id() functions together. Here’s
the syntax, which we’ll discuss extensively in a minute:
<xsl:for-each select="//address[generate-id(.)= generate-id(key('zipcodes', zip))]">
OK, let’s start digging through this syntax. We’re selecting all
<address> elements in which
the automatically generated
matches the automatically generated
id of the first node returned by the
key() function when we ask for ...