Shiva
Shiva

Reputation: 21

XSLT - Sum of node values using For each

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>

Upvotes: 2

Views: 4785

Answers (2)

mg_kedzie
mg_kedzie

Reputation: 437

<?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>

Upvotes: 0

mtt2p
mtt2p

Reputation: 1906

With sum() and catch all amount nodes

<xsl:value-of select="sum(//amount[. != ''])"/>

Upvotes: 2

Related Questions