XSLT - Sum of node values using For each

Viewed 3794

I have the following XML

    <T1>
    <amount>100</amount>
    </T1>

    <T1>
    <amount>100</amount>
    <T1>
...

Now I'm supposed to sum all the amount node values to a single variable or element

I'm very new to this domain

kindly suggest the possible XSLT1.0 code please

i'm expecting the output as <total>200</total>

2 Answers

With sum() and catch all amount nodes

<xsl:value-of select="sum(//amount[. != ''])"/>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" 
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<xsl:variable name="mySum" select="sum(//T1/amount)"/>
<xsl:template match="/">
    <total>
        <xsl:value-of select="$mySum"/>
    </total>
    <!--    <anothMethod>
        <xsl:value-of select="sum(//T1/amount)"/>
    </anothMethod> -->
</xsl:template>
</xsl:stylesheet>
Related