XML technologies / XSLT / XSLT Cookbook / Exploiting the potential of XSLT 2.0 / Prefer for-each-group to Muenchian grouping

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

XSLT 1.0 lacked explicit grouping support, so indirect and potentially confusing techniques had to be invented.

Solution

Use the powerful instruction xsl:for-each-group for grouping. Its required select attribute defines the population to group. One of four criteria, explained below, divides it into groups. While processing a group, function current-group( ) accesses every node in the current group. Function current-grouping-key( ) accesses the key defining the current group when grouping by value or adjacency. Function current-grouping-key( ) has no value when grouping by starting or ending nodes.

Sort groups by adding one or more xsl:sort instructions defining sort criteria, just as with xsl:for-each.

Grouping by value (group-by="ausdruck")

Reporting often poses classic grouping problems. With sales data, product managers may want groups by region, product type or salesperson, depending on their question. Attribute group-by defines an expression computing the values used to group population nodes. For example, group-by="@dept" groups nodes sharing the same dept value:

<xsl:template match="Employees">
  <EmployeesByDept>
    <xsl:for-each-group select="employee" group-by="@dept">
      <dept name="{current-grouping-key( )}">
        <xsl:copy-of select="current-group( )"/>
      </dept>
    </xsl:for-each-group>
  </EmployeesByDept>
</xsl:template>

Grouping adjacent nodes (group-adjacent="ausdruck")

In document processing, for example, nodes with equal values may belong together only if adjacent. Like group-by, group-adjacent defines a grouping-value expression. Equal-valued nodes join the same group only if adjacent in the population. The value of group-adjacent must have exactly one item; empty or multiple-item sequences cause an error.

Imagine a document of para elements interspersed with heading elements. You want to extract just the para elements while retaining the fact that some sequences of para elements belong to the same topic:

<xsl:template match="doc">
  <xsl:copy>
    <xsl:for-each-group select="*" group-adjacent="name( )">
      <xsl:if test="self::para">
        <topic>
          <xsl:copy-of select="current-group( )"/>
        </topic>
      </xsl:if>
    </xsl:for-each-group>
  </xsl:copy>
</xsl:template>

Grouping by starting nodes (group-starting-with="muster")

Particularly in documents, related nodes are often delimited by a title, subtitle or other heading. Starting-node grouping handles such loosely structured documents easily. Attribute group-starting-with defines a pattern matching each group’s starting node, like the patterns used by attribute match in xsl:template instructions. A matching node starts a group containing subsequent nodes up to the next match. The population’s first node starts a group whether it matches or not. Thus there is at least one group, the whole population, even if nothing matches.

A classic example reconstructs structure from an unstructured document. XHTML is loosely structured, especially its heading elements (h1, h2 etc.). This transformation restores structure by nesting groups starting with h1 in a div element:

<xsl:template match="body">
  <xsl:copy>
    <xsl:for-each-group select="*" group-starting-with="h1">
      <div>
        <xsl:apply-templates select="current-group( )"/>
      </div>
    </xsl:for-each-group>
  </xsl:copy>
</xsl:template>

Grouping by ending nodes (group-ending-with="muster")

This resembles group-starting-with but uses pattern group-ending-with to identify the current group’s final node. The population’s first node starts a group, so one exists even if nothing matches.

This is the least commonly applicable grouping method. Human-oriented documents usually introduce groups with headings rather than ending markers. In XSLT 2.0 Programmer's Reference Michael Kay gives an example of documents split for transmission, whose boundaries are marked by the absence of attribute continued='yes'. A more likely use adds structure by grouping elements according to an ending condition. For example, group paragraphs into sections of five:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:template match="doc">
    <xsl:copy>
      <xsl:for-each-group select="para" group-ending-with="para[position( ) mod 5 eq 0]">
        <section>
          <xsl:for-each select="current-group( )">
            <xsl:copy>
              <xsl:apply-templates select="@*|node( )"/>
            </xsl:copy>
          </xsl:for-each>
        </section>
      </xsl:for-each-group>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="@* | node( )">
    <xsl:copy>
      <xsl:apply-templates select="@* | node( )"/>
    </xsl:copy>
   </xsl:template>
</xsl:stylesheet>

Discussion

The Muenchian method, named after Steve Muench of Oracle, was an innovative XSLT 1.0 grouping technique. It indexed documents with keys, efficiently finding unique grouping keys and then processing all nodes for each group:

<xsl:key name="products-by-category" select="product" use="@category"/>
<xsl:template match="/">
  <xsl:for-each select="//product[count(. | key('products-by-category', @category)[1])= 1]">
    <xsl:variable name="current-grouping-key" select="@category"/>
    <xsl:variable name="current-group" select="key('current-grouping-key', $current-grouping-key)"/>
    <xsl:for-each select="$current-group/*">
      <!-- processing for elements in group -->
      <!-- you can use xsl:sort here also, if necessary -->
    </xsl:for-each/>
  </xsl:for-each/>
</xsl:template>

Muenchian grouping still works in 2.0, but prefer for-each-group. It is probably at least as efficient and possibly faster. Equally important, it is clearer, especially to beginners, and one instruction supports all four grouping modes. Muenchian grouping handles only value-based groups. Backward compatibility with XSLT 1.0 is probably the only compelling reason to retain it in XSLT 2.0.

  

 

 

 

back to top