O'Reilly logo

XSLT, 2nd Edition by Doug Tidwell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required