ShresthaR
ShresthaR

Reputation: 1274

sum xml attribute in xslt not working

<data>
    <assets>
        <details amount="100"/>
        <details amount="50"/>
        <details amount="30"/>
    </assets>
</data>

I would like to add amount attributes from data/assets/details by using sum function inside xslt. I did in following way which gives type conversion error

<xsl:value-of select="sum(/data/assets/details/@amount)"/>

Upvotes: 0

Views: 309

Answers (2)

Michael Kay
Michael Kay

Reputation: 163595

Your revised information indicates that you have amount values in the format 123,456.78. This is not a format that the automatic string-to-number conversion can handle.

So you need to do a conversion, and then you need to sum over the converted values. This is very easy in XSLT 2.0:

sum(/data/assets/details/@amount/number(translate(., ',', ''))

It's a lot more difficult in XSLT 1.0; the only clean solution is a recursive template that converts and adds each value in turn.

Upvotes: 2

siva2012
siva2012

Reputation: 459

Kindly try the below XSLT for result:

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="assets">
<xsl:value-of select="details[1]/@amount + details[2]/@amount + details[3]/@amount"/>
</xsl:template>
</xsl:stylesheet>

Upvotes: 0

Related Questions