Loading ...
Sorry, an error occurred while loading the content.

3387Re: [XSL-FO] compute running totals

Expand Messages
  • G. Ken Holman
    May 1, 2003
      At 2003-05-01 03:00 +0000, evildan_2000 wrote:
      >I have an XML in the following format:
      >I want to sum up the amount in xsl,
      ><xsl:value-of select="sum(/item/amount)"> doesn't work and returns
      >NaN, I can not change how amount is formatted in the XML.
      >I was wondering if anyone knows a solutions to this ?
      >I am thinking of using translate() and number() function to format
      >each amount individually and then add them up

      Precisely. The commas are getting in your way. Using translate() you can
      remove the commas and obtain a value suitable for summing.

      >....the problem is that
      >I can't find a way to keep an accumulating sum.

      It involves "walking" through the tree one node at a time: starting at the
      first and then walking individually to each of the following siblings. An
      example is below. I also included putting the commas back in on the way
      out again.

      I hope this helps.

      ........................... Ken

      t:\ftemp>type daniel.xml
      <?xml version="1.0" encoding="iso-8859-1"?>
      <item id="0">
      <item id="1">
      <item id="2">
      t:\ftemp>type daniel.xsl
      <?xml version="1.0" encoding="iso-8859-1"?>
      <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

      <xsl:template match="/">
      <xsl:value-of select="sum( /items/item )"/>
      <xsl:apply-templates mode="do-sum-no-commas" select="/items/item[1]"/>

      <xsl:template mode="do-sum-no-commas" match="item">
      <xsl:param name="sum" select="0"/>
      <xsl:variable name="running-sum"
      select="$sum + number(translate(amount,',',''))"/>
      <xsl:when test="following-sibling::item">
      <xsl:apply-templates mode="do-sum-no-commas"
      <xsl:with-param name="sum" select="$running-sum"/>
      <xsl:value-of select="format-number( $running-sum, '#,##0.00' )"/>

      t:\ftemp>xt daniel.xml daniel.xsl
      <?xml version="1.0" encoding="utf-8"?>

      Upcoming hands-on courses: Europe (XSLT/XPath): May 5, 2003
      - Europe (XSL-FO): May 16, 2003
      - (XSLT/XPath and/or XSL-FO) North America: June 16-20, 2003

      G. Ken Holman mailto:gkholman@...
      Crane Softwrights Ltd. http://www.CraneSoftwrights.com/f/
      Box 266, Kars, Ontario CANADA K0A-2E0 +1(613)489-0999 (F:-0995)
      ISBN 0-13-065196-6 Definitive XSLT and XPath
      ISBN 0-13-140374-5 Definitive XSL-FO
      ISBN 1-894049-08-X Practical Transformation Using XSLT and XPath
      ISBN 1-894049-10-1 Practical Formatting Using XSL-FO
      Male Breast Cancer Awareness http://www.CraneSoftwrights.com/f/bc
    • Show all 2 messages in this topic