Q:

XSLT for grouping and summing values

I am a newbie to XSLT and am having trouble accomplishing a result and I come here in case anyone can help me.
I have the following XML:
<funds>
    <bags>
        <bag name="BAG_USD_MAIN" value="10.0" type="USD">
            <pockets>
                <pocket name="bank" value="7.5">
                <pocket name="award" value="2.5">
            </pockets>
         </bag>
        <bag name="BAG_USD_SAVINGS" value="290.75" type="USD">
            <pockets>
                <pocket name="bank" value="290.75">
            </pockets>
         </bag>
        <bag name="BAG_EUR_EXTRA" value="890.0" type="EUR">
            <pockets>
                <pocket name="bank" value="753.0">
                <pocket name="bank_eng" value="137.0">
            </pockets>
         </bag>
    </bags>
 </funds>

And I'd like to be able to transform it this way:
<result>
    <total type="USD">375.0</total>
    <total type="EUR">890.0</total>
</result>

Is it possible with XSLT?
Thank you,
Regards
TS

A:

Because you are using XSLT 2.0 you can use the <xsl:for-each-group> element to group elements by @type and then use sum() to sum the elements in the group.
The following stylesheet solves what you are trying to do:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <!-- Match the bags element  -->
    <xsl:template match="bags">
        <result>
            <!-- Group each bag element by its type -->
            <xsl:for-each-group select="bag" group-by="@type">
                <!-- Use the current key to display the type attribute -->
                <total type="{current-grouping-key()}">
                    <!-- Sum all the elements from the current group -->
                    <xsl:value-of select="sum(current-group()/@value)" />
                </total>
            </xsl:for-each-group>
        </result>
    </xsl:template>

</xsl:stylesheet>

Just for completeness an XSLT 1.0 solution would be based on Muenchian Grouping.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <!-- Index all bag elements withing bags element using their
         type attribute by using a key -->
    <xsl:key name="currency-key"
             match="/funds/bags/bag"
             use="@type" />

    <!-- Match bags element -->
    <xsl:template match="bags">
        <result>
            <!-- Match the first bag element for a specific group -->
            <xsl:apply-templates select="bag[generate-id() = generate-id(key('currency-key', @type)[1])]" />
        </result>
    </xsl:template>

    <xsl:template match="bag">
        <total type="{@type}">
            <!-- Sum all the elements from the @type group -->
            <xsl:value-of select="sum(key('currency-key', @type)/@value)" />
        </total>
    </xsl:template>

</xsl:stylesheet>

