Mark A. Tagliaferro
Mark A. Tagliaferro

Reputation: 157

XSLT with grouping and group totals

I have the following XML data. I have no control on the structure of this data, this is how I'm receiving it.

<data>
  <row>
    <value name="CustomerID">1</value>
    <value name="CustomerName">Joe</value>
    <value name="Cost">22.50</value>
  </row>
  <row>
    <value name="CustomerID">1</value>
    <value name="CustomerName">Joe</value>
    <value name="Cost">55.50</value>
  </row>
  <row>
    <value name="CustomerID">2</value>
    <value name="CustomerName">Jane</value>
    <value name="Cost">10</value>
  </row>
  <row>
    <value name="CustomerID">2</value>
    <value name="CustomerName">Jane</value>
    <value name="Cost">13.50</value>
  </row>
    <row>
    <value name="CustomerID">3</value>
    <value name="CustomerName">Jim</value>
    <value name="Cost">50</value>
  </row>
</data>

I need to use XSLT v1.0 to display the data grouped by Customer ID and with a total for each customer. I've tried searching many articles but nothing has this kind of strange structure.

Upvotes: 1

Views: 219

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56222

Use:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:key name="k" match="row" use="value[@name = 'CustomerID']"/>

    <xsl:template match="data">
        <xsl:copy>
            <xsl:apply-templates select="row[generate-id(.) = generate-id(key('k', value[@name = 'CustomerID']))]"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="row">
        <xsl:copy>
            <xsl:copy-of select="value[@name = 'CustomerID']"/>
            <xsl:copy-of select="value[@name = 'CustomerName']"/>
            <sum>
                <xsl:value-of select="sum(key('k', value[@name = 'CustomerID'])/value[@name = 'Cost'])"/>
            </sum>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Output:

<data>
  <row>
    <value name="CustomerID">1</value>
    <value name="CustomerName">Joe</value>
    <sum>78</sum>
  </row>
  <row>
    <value name="CustomerID">2</value>
    <value name="CustomerName">Jane</value>
    <sum>23.5</sum>
  </row>
  <row>
    <value name="CustomerID">3</value>
    <value name="CustomerName">Jim</value>
    <sum>50</sum>
  </row>
</data>

Upvotes: 3

Related Questions