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:

  1. Define a key for the property we want to use for grouping.

  2. Select all of the nodes we want to group. We’ll do some tricks with the key() and generate-id() functions to find the unique grouping values.

  3. 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 ...

Get XSLT, 2nd Edition 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.