RE: [xsl] XSLT 2.0 multi-level grouping challenge/problem

Subject: RE: [xsl] XSLT 2.0 multi-level grouping challenge/problem
From: "Bjorndahl, Brad" <brad.bjorndahl@xxxxxxxxxxxxxxxx>
Date: Thu, 24 May 2007 12:12:51 -0400
I did something like this recently. I tested this with your xml (which
needed a little fixing).


<xsl:transform version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
  xmlns:xs="http://www.w3.org/2001/XMLSchema";>

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/donors">
    <xsl:variable name="DONORS" >
      <DONORS>
        <xsl:for-each-group select="donor" group-by="state" >
          <state name="{current-grouping-key()}" >

            <xsl:for-each-group select="current-group()" group-by="city"
>
              <city  name="{current-grouping-key()}" >

                <xsl:for-each-group select="current-group()"
group-by="organ">
                  <organ name="{current-grouping-key()}"><xsl:value-of
select="count(current-group())" /></organ>

                </xsl:for-each-group>
              </city>
            </xsl:for-each-group>
          </state>
        </xsl:for-each-group>
      </DONORS>
    </xsl:variable>
    <xsl:apply-templates select="$DONORS" />
  </xsl:template>

  <xsl:template match="DONORS" >
    <table border="1">
      <tr>
        <th>State</th>
        <th>City</th>
        <th>Organ</th>
        <th>count</th>
      </tr>
      <xsl:apply-templates />
    </table>
  </xsl:template>

  <xsl:template match="state" >
    <tr>
      <td rowspan="{count(city/organ)}" ><xsl:value-of select="@name"
/></td>
      <xsl:apply-templates />
    </tr>
  </xsl:template>

  <xsl:template match="city" >
    <xsl:choose>
      <xsl:when test="position() eq 1" >
        <td rowspan="{count(organ)}"><xsl:value-of select="@name"
/></td>
        <xsl:apply-templates />
      </xsl:when>
      <xsl:otherwise>
        <tr>
          <td rowspan="{count(organ)}"><xsl:value-of select="@name"
/></td>
          <xsl:apply-templates />
        </tr>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="organ" >
    <xsl:choose>
      <xsl:when test="position() eq 1" >
        <td><xsl:value-of select="@name" /></td>
        <td><xsl:value-of select="." /></td>
      </xsl:when>
      <xsl:otherwise>
        <tr>
          <td><xsl:value-of select="@name" /></td>
          <td><xsl:value-of select="." /></td>
        </tr>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:transform>

Brad

Current Thread