XML technologies / XSLT / Reference: XSLT 1.0 and 2.0 elements / for-each-group

(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 6.)

A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z

 

Instruction xsl:for-each-group groups sequence items, nodes or atomic values, by matching strings, names, document or sequence positions, or other XPath-computable properties.

Classification

Instruction

Function group

Groups from an input sequence

Introduced in

XSLT 2.0

Stylesheet position and permitted contents:

xsl:for-each-group can occur anywhere inside template rules defined by xsl:template.

Content of element xsl:for-each-group may start with any number of elements xsl:sort sorting the groups. Following XSLT instructions, literal result elements and text form an output sequence constructor in any order and number.

Attributes:

Standard attributes apply. Instruction xsl:for-each-group also has attributes assembling the grouped sequence.

Except select, which constructs the population, these are optional but constrained: exactly one of group-by, group-adjacent, group-starting-with and group-ending-with must be used. Attribute collation requires either group-by or group-adjacent.

collation

Value

{uri} (also as an AVT)

Usage

Optional

Introduced in

XSLT 2.0

Attribute collation loads string-comparison rules when needed. Attribute collation is allowed only with group-by or group-adjacent, since other rules require nodes only. It can contain an AVT.

group-adjacent

Value

xpath-expression

Usage

Optional

Introduced in

XSLT 2.0

The evaluated XPath expression from attribute group-adjacent applies to items in their original order (population order). Consecutive items in population order with equal grouping values form a group. Each item differing from its predecessor starts a new group.

Note: Unlike group-by, this happens even for values used by an existing group. Group count can exceed distinct-value count when sequence order requires it.

group-by

Value

xpath-expression

Usage

Optional

Introduced in

XSLT 2.0

Attribute group-by uses XPath to determine group membership. All equal grouping values share a group; group count equals distinct grouping-value count.

An item may belong to several groups. With attribute group-by, attribute collation is also allowed.

group-ending-with

Value

xpath-pattern

Usage

Optional

Introduced in

XSLT 2.0

Attribute group-ending-with uses an XPath pattern, so input must contain only nodes or an error occurs. The pattern selects each group’s last member, examining nodes in sequence order.

The first group starts at the first node and ends at the first match. A matching first node forms a group alone. Each next group starts immediately after a match and continues through the next matching node. For n matches there are that many groups, plus one if the last node does not match.

group-starting-with

Value

xpath-pattern

Usage

Optional

Introduced in

XSLT 2.0

Attribute group-starting-with uses an XPath pattern, requiring nodes-only input or raising an error. The pattern selects the first member, examining nodes in sequence order.

The first group always starts with the first node, matching or not. Each matching later node starts a new group containing subsequent nodes until the next match. For n matches there are that many groups, plus one if the first node does not match.

select

Value

xpath-expression

Usage

Mandatory

Introduced in

XSLT 2.0

Mandatory attribute select assembles items to group according to exactly one mutually exclusive criterion: group-by, group-adjacent, group-starting-with or group-ending-with.

Note: With group-starting-with or group-ending-with, input must contain nodes only. Other rules permit any item type.

Purpose:

Instruction xsl:for-each-group fills a painful XSLT 1.0 gap. It simplifies cumbersome node grouping and extends it to arbitrary sequence items.

Input sequence (population)
Evaluate attribute select to get the input population, with its population order. Each member belongs to one group in the general case; see note on attribute group-by. Item count is context size.

Assembling groups
Instruction xsl:for-each-group partitions its population into subsequences. Empty input creates zero groups.

Membership uses group-by or group-adja­cent with a common grouping key, or group-starting-with or group-ending-with with a pattern matching the first member. Groups cannot be empty: each has at least one item. Each group instantiates the instruction body.

Grouping keys
Values of attribute group-by or group-adjacent produce a key evaluated on each item, treated as context item with its sequence position as context position.

Normally strings are compared unless an additional attribute as sets another datatype. Collation rules may guide string comparison.

Failed conversion to the required type is an error. A grouping key equal to NaN groups with other such items, although elsewhere in XSLT NaN is unequal to itself.

Group processing order
After grouping, one or more instructions xsl:sort as direct children of xsl:for-each-group can sort groups. Each group is then processed with all members in the new order. Member order within groups stays unchanged.

Without sorting by xsl:sort, groups follow order of first appearance (order of first appearance): their first members’ positions determine processing order.

Processing groups
Each group instantiates the body of xsl:for-each-group as the current group. Its first member (initial item) is context item; group count is context size; group position is context position. Functions fn:position() and fn:last() return these values.

In the body, function current-group() returns group members as a sequence, for example to output their string values with xsl:value-of. At least one item is returned because groups are nonempty.

Function current-grouping-key() returns the current grouping-key value.

Note – No activation of further rules:
Since xsl:for-each-group constructs its own sequence and clears the current template rule, instructions xsl:apply-imports or xsl:next-match cannot activate rules from inside it.

Examples:

Example 1 – Grouping with group-by:

Source document:
Input lists songs, with artist and title as attributes.

<lieder>
  ...
  <lied name="She loves you" kuenstler="Beatles"/>
  <lied name="Yesterday" kuenstler="Beatles "/>
  <lied name="Satisfaction" kuenstler="Rolling Stones"/>
  <lied name="My Generation" kuenstler="Who"/>
  <lied name="Under My Thumb" kuenstler="Rolling Stones"/>
  ...
</lieder>

Group songs by artist as comma-separated lists. Output a table with one artist and their songs per row.

Result document:

<table>
  <tr>
    <th>Künstler</th>
    <th>Stückliste</th>
  </tr>
  <tr>
    <td>Beatles</td>
    <td>She Loves You, Yesterday</td>
  </tr>
  <tr>
    <td>Rolling Stones</td>
    <td>Satifaction, Under My Thumb</td>
  </tr>  
  <tr>
    <td>Who</td>
    <td>My Generation</td>
  </tr>
  ...
</table>

XSLT stylesheet:

<xsl:template match="/">
  <table>
    <tr>
      <th>Künstler</th>
      <th>Stückliste</th>
    </tr>
    <xsl:for-each-group select="lieder/lied" group-by="@kuenstler">
      <tr>
        <td><xsl:value-of select="current-grouping-key()"/></td>
        <td><xsl:value-of select="current-group()/@name" separator=","/></td>
      </tr>
    </xsl:for-each-group>
  </table>
</xsl:template>

Use xsl:for-each-group with attribute group-by and grouping key from the string value of attribute kuenstler:

<xsl:for-each-group select="lieder/lied" group-by="@kuenstler">

The artist name output by xsl:value-of comes from function current-grouping-key():

<xsl:value-of select="current-grouping-key()"/>

Alternatively use attribute kuenstler of the first group member, the context item in the body. All members have the same value:

<!-- Alternative --> <xsl:value-of select="@kuenstler"/>

Output song titles with xsl:value-of using function current-group() to retrieve attributes name of all members returned as a sequence:

<xsl:value-of select="current-group()/@name" separator=","/>

The comma separator comes from attribute separator, added to this instruction in XSLT 2.0.

Example 2 – Grouping with group-starting-with:

Source document:

<body>
  <h2>Sektionen in XHTML 2.0</h2>
  <p>Dem body wird eine Sektion untergeordnet.</p>
  <p>Diese Sektion kann wieder mehrere Sektionen enthalten.</p>
  <h2>Überschriften in Sektionen</h2>
  <p>Jeder Sektion können Überschriften zugeordnet werden.</p>
  <p>Die Hierarchie der Sektion bestimmt den Überschriftsgrad.</p>
  <p>Deshalb kann ein allgemeines Element 'h' verwendet werden.</p>
</body>

Convert XHTML 1.0 to XHTML 2.0, dividing content into sections, each with a heading. A heading <h2> and following containers <p> belong to one section, grouping adjacent containers <p> with their preceding heading <h2>.

Result with sections:

<body>
  <section>
    <section>
      <h>Sektionen in XHTML 2.0</h>
      <p>Dem body wird eine Sektion untergeordnet.</p>
      <p>Diese Sektion kann wieder mehrere Sektionen enthalten.</p>
    </section> 
    <section>
      <h>Überschriften in Sektionen</h>
      <p>Jeder Sektion können Überschriften zugeordnet werden.</p>
      <p>Die Hierarchie der Sektion bestimmt den Überschriftsgrad.</p>
      <p>Deshalb kann ein allgemeines Element 'h' verwendet werden.</p>
    </section>
  </section>
<body>

XSLT stylesheet:

<xsl:template match="body">
  <section>
    <xsl:for-each-group select="*" group-starting-with="h2">
      <section>
        <h><xsl:value-of select="current-group()[self::h2]"/></h>
        <xsl:for-each select="current-group()[self::p]">
          <xsl:copy-of select="."/>
        </xsl:for-each> 
      </section>
    </xsl:for-each-group>
  </section>
</xsl:template>

Attribute select of element xsl:for-each-group selects all elements with wildcard NameTest "*". Attribute group-star­ting-with="h2" partitions them into groups starting with element <h2>. Output it first, then use xsl:for-each (loop ) to copy all containers <p> of the group to the result.

Output uses the entire group sequence from current-group(). A predicate selects node types using self::h2 or self::p to avoid ambiguity. If the first group does not start with element <h2>, its container <h> remains empty.

Example 3 – Grouping with group-adjacent:

Source document:

<p>Überprüfen Sie <em>unbedingt</em>:
  <ul>
    <li>Warnblinkanlage,</li>
    <li>Bremslicht,</li>
    <li>Reifendruck</li>
  </ul> vor jeder längeren Fahrt.</p>

Improve this document so container <p> does not contain the list.

Result document:

<p>Überprüfen Sie <em>unbedingt</em>:</p>
<ul>
  <li>Warnblinkanlage,</li>
  <li>Bremslicht,</li>
  <li>Reifendruck</li>
</ul>
<p>vor jeder längeren Fahrt.</p>

Wrap a container <p> around consecutive nodes other than elements <ul>, using group-adjacent in xsl:for-each-group.

XSLT stylesheet:

<xsl:template match="p">
  <xsl:for-each-group select="node()" group-adjacent="self::ul">
    <xsl:choose>
      <xsl:when test="self::ul">
        <xsl:copy-of select="current-group()"/>
      </xsl:when>
      <xsl:otherwise>
        <p><xsl:copy-of select="current-group()"/></p>
      </xsl:otherwise>  
    </xsl:choose>
  </xsl:for-each-group>
</xsl:template>

The template matches element <p>. Instruction xsl:for-each-group uses select="node()" to select every child node as population. Group using group-adjacent, assigning adjacent items with equal keys to one group:

<xsl:for-each-group select="node()" group-adjacent="self::ul">

Here criterion group-adjacent="self::ul" is boolean: each context item either is an element <ul> or is not.

Three groups result: first a text node and an element <em>, then an element <ul>, then another text node.

Process each group in turn, checking whether its first member is an element <ul>. If so, copy the whole group:

<xsl:when test="self::ul">
  <xsl:copy-of select="current-group()"/>
</xsl:when>

Only the first member is context item here, not every member. Our sequence current-group() has one item, but multiple consecutive lists would behave identically.

Other groups are output wrapped in container <p>:

<xsl:otherwise>
  <p><xsl:copy-of select="current-group()"/></p>
</xsl:otherwise>

Function current-group() copies all group members as a sequence inside container <p> in the result.

Element definition:

XSLT 1.0:

Element unavailable in XSLT 1.0.

XSLT 2.0:

<!-- Category: instruction -->
<xsl:for-each-group
     select = expression
     group-by? = expression
     group-adjacent? = expression
     group-starting-with? = pattern
     group-ending-with? = pattern
     collation? = { uri-string }>

     <!-- Content: (xsl:sort*, sequence-constructor) -->
</xsl:for-each-group>

   

  

back to top