Web Services, Part V: XML and XSLT Programming: Adding Up XML Numbers - Doc JavaScript | WebReference

Web Services, Part V: XML and XSLT Programming: Adding Up XML Numbers - Doc JavaScript

Web Services, Part V: XML and XSLT Programming

Adding Up XML Numbers

You can use XSLT to add up data within identical tags. Suppose you have the following XML section:

  <name>January 2001</name>
  <week number="1" dvds_rented="12000" />
  <week number="2" dvds_rented="15000" />
  <week number="3" dvds_rented="18000" />
  <week number="4" dvds_rented="11800" />

To add all dvds_rented during all four weeks, you will write:

<xsl:value-of select="sum(week/@dvds_rented)"/>

You need to insert this line inside a loop where the value of month is known. Something like this:

<xsl:for-each select="//data/month">
<xsl:value-of select="sum(week/@dvds_rented)"/>

Use the format-number() method to pretty-print the sum:

<xsl:value-of select="format-number(sum(week/@dvds_rented),

Here is the XSLT file that converts the MyDVD XML file (try it)(view it):

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="
  http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<TITLE><xsl:value-of select="//summary/heading"/></TITLE>
<H1><xsl:value-of select="//summary/heading"/></H1>
<H2><xsl:value-of select="//summary/subhead"/></H2>
<P><xsl:value-of select="//summary/description"/></P>
<xsl:for-each select="//data/month[1]/week">
<TH>W<xsl:value-of select="@number"/></TH>
<xsl:for-each select="//data/month">
   <th style="text-align:left"><xsl:value-of select="name"/></th>
   <xsl:for-each select="week">
     <td style="text-align:right">
       <xsl:value-of select="format-number(@dvds_rented, '###,###')"/>
	<td style="text-align:right;font-weight:bold">
	 <xsl:value-of select="format-number(sum(week/@dvds_rented),

Here is the output:

Next: How to define and use variables in XSLT


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: December 31, 2001
Revised: December 31, 2001

URL: http://www.webreference.com/js/column100/7.html