Page 1 of 1
cumulative addition inside for loop in xslt
Posted: Wed Nov 18, 2009 5:13 pm
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
Re: cumulative addition inside for loop in xslt
Posted: Wed Nov 18, 2009 6:27 pm
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.
Re: cumulative addition inside for loop in xslt
Posted: Thu Nov 19, 2009 3:49 pm
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