Re: [xsl] how to apply sum to a comma delimited list

Subject: Re: [xsl] how to apply sum to a comma delimited list
From: Mike Brown <mike@xxxxxxxx>
Date: Wed, 15 May 2002 12:05:16 -0600 (MDT)
Florin Dragu wrote:
> is there any way that I can use sum() functions in XSLT on a comma separated
> list (received as an output from a template)?

It would be easiest if when you built the comma-separated list, you created a
result tree fragment in which each value you want in the total is in a
separate element. The string-value of the fragment can still give you the list
output that you want, but you can also use XPath/XSLT's sum function on the
node-set equivalent of the fragment. xalan:nodeSet() (or exsl:node-set() if
you're using a more recent snapshot of Xalan) will convert the RTF to a

The most portable alternative is to use a recursive template to dissect the

Given XML:

<?xml version="1.0"?>

Here's a stylesheet that demonstrates both solutions:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
                exclude-result-prefixes="xalan exsl">
<xsl:output method="text"/>

<xsl:template match="/">
  <xsl:variable name="list">
    <xsl:for-each select="some/data">
        <xsl:value-of select="."/>
      <xsl:if test="position() != last()">
  <xsl:text>The list is: </xsl:text>
  <xsl:value-of select="$list"/>
  <xsl:text>&#10;The sum is: </xsl:text>
    <xsl:when test="function-available('exsl:node-set')">
      <xsl:value-of select="count(exsl:node-set($list)/dummyElement)"/>
    <xsl:when test="function-available('xalan:nodeSet')">
      <xsl:value-of select="sum(xalan:nodeSet($list)/dummyElement)"/> 
      <xsl:call-template name="sum">
        <xsl:with-param name="str" select="string($list)"/>

<xsl:template name="sum">
  <xsl:param name="str"/>
  <xsl:param name="total" select="0"/>
    <xsl:when test="contains($str,',')">
      <xsl:call-template name="sum">
        <xsl:with-param name="str" select="substring-after($str,',')"/>
        <xsl:with-param name="total" select="$total + substring-before($str,',')"/>
      <xsl:value-of select="$total + $str"/>


   - Mike
  mike j. brown                   |  xml/xslt:
  denver/boulder, colorado, usa   |  resume:

 XSL-List info and archive:

Current Thread