XSLT 2.0, XSLT 1.0. :
<xsl:template match="number">
<xsl:call-template name="sumdigits">
<xsl:with-param name="number" select="." />
</xsl:call-template>
</xsl:template>
<xsl:template name="sumdigits">
<xsl:param name="number" />
<xsl:param name="runningtotal">0</xsl:param>
<xsl:choose>
<xsl:when test="string-length($number) = 0">
<xsl:value-of select="$runningtotal" />
</xsl:when>
<xsl:otherwise>
<xsl:variable name="lastdigit" select="substring($number, string-length($number), 1)" />
<xsl:variable name="newrunningtotal" select="number($runningtotal) + number($lastdigit)" />
<xsl:call-template name="sumdigits">
<xsl:with-param name="number" select="substring($number, 1, string-length($number) - 2)" />
<xsl:with-param name="runningtotal" select="$newrunningtotal" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
It works by getting the last digit in the input, adding it to the "current total" and recursively calling the named template with the last two digits of the remote input. When there are no numbers left, the total amount is returned.
This XSLT snippet assumes the input is in XML inside an element named 'number'
<number>123456789</number>
The result should be 25. As you can see, doing this in XSLT2.0 would be much nicer.
Tim c source
share