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:
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. Because thekey()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:
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.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 ...
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