XSLT 1.0
キー「状態」を定義します。これから、状態名を指定してすべての状態を簡単に選択できます。Muenchianグループ化を適用して、入力内の一意の状態を見つけるよりも。
それからそれは簡単になります。「要素」テンプレートは州名ごとに1回適用され、key()を使用してその州のすべてのエントリをフェッチします。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:key name="state" match="element" use="@State" />
<xsl:template match="root">
<body>
<xsl:apply-templates select="element[generate-id(.)=generate-id(key('state',@State)[1])]"/>
</body>
</xsl:template>
<xsl:template match="element">
<h2><xsl:value-of select="@State" /></h2>
<table>
<xsl:for-each select="key('state',@State)">
<tr>
<td>
<xsl:value-of select="@County" />
</td>
<td>
<xsl:value-of select="@Population" />
</td>
</tr>
</xsl:for-each>
<tr>
<td>
<xsl:text>Total</xsl:text>
</td>
<td>
<xsl:value-of select="sum(key('state',@State)/@Population)"/>
</td>
</tr>
</table>
</xsl:template>
</xsl:stylesheet>
XSLT 2.0
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:template match="root">
<body>
<xsl:for-each-group select="element" group-by="@State">
<h2><xsl:value-of select="@State" /></h2>
<table>
<xsl:for-each select="current-group()">
<tr>
<td>
<xsl:value-of select="@County" />
</td>
<td>
<xsl:value-of select="@Population" />
</td>
</tr>
</xsl:for-each>
<tr>
<td>
<xsl:text>Total</xsl:text>
</td>
<td>
<xsl:value-of select="format-number(sum(current-group()/@Population), '#########')"/>
</td>
</tr>
</table>
</xsl:for-each-group>
</body>
</xsl:template>
</xsl:stylesheet>