The Most Common Grouping Style: group-by

As we just mentioned, everything we’ll do with grouping in XSLT 2.0 revolves around the new <xsl:for-each-group> element. This works much like <xsl:for-each>. In <xsl:for-each>, in each iteration we process an item in a sequence; with <xsl:for-each-group>, in each iteration we process a group. Thinking back to our addresses example, each group represents a unique zip code. When using <xsl:for-each-group>, the first group would be 00218, the second group would be 02718, and so forth.

To repeat from our discussion of the Muench method, we needed to do three things to group items in XSLT 1.0:

  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. Because the key() function returns a node-set, we can do further sorts on the set of nodes that match any given grouping value.

With XSLT 2.0, we need to do the same basic things, but we don’t have to get bogged down with key() and generate-id(). Our tasks are as follows:

  1. Define an XPath expression for the property we want to use for grouping. All we have to do is define the XPath expression—we don’t need a key.

  2. Select all of the nodes we want to group. We select all the nodes with an XPath expression. The XSLT processor takes all the items that match this expression and groups ...

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.