The <xsl:key> Approach
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:
Define a
keyfor the property we want to use for grouping.Select all of the nodes we want to group. We’ll do some tricks with the
key()andgenerate-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"/>
This <xsl:key> element
defines a new index called zipcodes. It indexes <address> elements based on the value
of the <zip> element they
contain.
Now that we’ve defined our key, we’re ready for the complicated part.
We use the key() and 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)[1])]">OK, let’s start digging through this syntax. We’re selecting all
<address> elements in which
the automatically generated id
matches the automatically generated id of the first node returned by the
key() function when we ask for ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access