[2.0] New Grouping Syntax in XSLT 2.0

In 2001, the XSL Working Group released a document entitled “XSLT Requirements Version 2.0.” More than half of the document came under the heading “Must Simplify Grouping.” (I can’t imagine how the group would have met a requirement named “Must Make Grouping More Complicated and Confusing.”) We’ll take a look at those changes in this section.

XSLT 2.0’s grouping functions are built around the <xsl:for-each-group> element. Within this element, we’ll use the new XSLT functions current-group() and current-grouping-key() to work with the data we’re grouping. There are four mutually exclusive attributes for the <xsl:for-each-group> element, each of which performs a different style of grouping:

group-by

This is the most common type of grouping. We use an XPath expression to define what identifies a group (all of the <address> elements that have the same <zip> code, for example), so we can then iterate through each group.

group-adjacent

This approach is useful when you want to build a group containing all the adjacent nodes that match an XPath expression. As an example, we’ll take all the adjacent <p> elements in a document, convert each one to an <li> element, and put <ul> and </ul> tags around the entire group.

group-starting-with

The group-starting-with attribute defines an XPath expression that identifies the start of a group. Once a group starts, every element is added to the group until the start of another group is found. group-starting-with and

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.