一个可能的 Xslt 1.0 解决方案是
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes"/>
<xsl:key name="kCustomer" match="item" use="@customer_id"/>
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="purchases">
<xsl:element name="table">
<xsl:element name="tr">
<xsl:element name="th">Customer ID</xsl:element>
<xsl:element name="th">Number of Items Purchased</xsl:element>
<xsl:for-each select="item[generate-id(.) = generate-id(key('kCustomer', @customer_id))]">
<xsl:variable name="total" select="count(/purchases/item[@customer_id=current()/@customer_id]/@id)" />
<xsl:element name="tr">
<xsl:element name="td">
<xsl:value-of select="./@customer_id" />
</xsl:element>
<xsl:element name="td">
<xsl:value-of select="$total" />
</xsl:element>
</xsl:element>
</xsl:for-each>
</xsl:element>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
取自Dimitres关于How can I Group and sort based on sum 的回答。
正如 Dimitre 所指出的,购买模板可以简化为
<xsl:template match="purchases">
<table>
<tr>
<th>Customer ID</th>
<th>Number of Items Purchased</th>
</tr>
<xsl:for-each select="item[generate-id(.) = generate-id(key('kCustomer', @customer_id))]">
<xsl:variable name="total" select="count(/purchases/item[@customer_id=current()/@customer_id]/@id)" />
<tr>
<td>
<xsl:value-of select="./@customer_id" />
</td>
<td>
<xsl:value-of select="$total" />
</td>
</tr>
</xsl:for-each>
</table>
</xsl:template>