cumulative addition inside for loop in xslt

Here should go questions about transforming XML with XSLT and FOP.
cashreadbob
Posts: 3
Joined: Sun Aug 03, 2008 5:07 pm

cumulative addition inside for loop in xslt

Post by cashreadbob »

Hi iam using XSLT 1.0 version.

I have a xsl:for-each loop where i declared a variable for some manupulations.So for each and every iteration the variable value changes. I want to sum up the values inside the loop.I guess we can not use sum() as it delas with nodes only.Can somebody help me plz..

Thanks in advance
Uday
cashreadbob
Posts: 3
Joined: Sun Aug 03, 2008 5:07 pm

Re: cumulative addition inside for loop in xslt

Post by cashreadbob »

somehow i able to construct String like like 10+20+30. I wanted to get the total as number i.e 60.we can not say number(10+20+30).b'coz..+ is a string.so it gives us NaN.
george
Site Admin
Posts: 2095
Joined: Thu Jan 09, 2003 2:58 pm

Re: cumulative addition inside for loop in xslt

Post by george »

You can check if your processor has an evaluate extension. For example if you use Saxon 6.5 then you can use the saxon:evaluate extension. A solution independent of the XSLT processor can use a recursive named template to evaluate the expression. You find both solutions in the stylesheet sample below:

Code: Select all


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

<xsl:variable name="expression">20+40+30</xsl:variable>

<xsl:template match="/">
<test>
<expression>
<xsl:value-of select="$expression"/>
</expression>
<extension>
<xsl:value-of select="saxon:evaluate($expression)"/>
</extension>
<template>
<xsl:call-template name="sum">
<xsl:with-param name="expression" select="$expression"/>
</xsl:call-template>
</template>
</test>
</xsl:template>

<xsl:template name="sum">
<xsl:param name="expression"/>
<xsl:param name="value" select="0"/>
<xsl:choose>
<xsl:when test="$expression=''">
<xsl:value-of select="$value"/>
</xsl:when>
<xsl:when test="not(contains($expression, '+'))">
<xsl:value-of select="$value + number($expression)"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="sum">
<xsl:with-param name="expression" select="substring-after($expression, '+')"/>
<xsl:with-param name="value" select="$value + number(substring-before($expression, '+'))"
/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Best Regards,
George
George Cristian Bina
Post Reply