Operate on Data Values

MSXML 5.0 SDK

Microsoft XML Core Services (MSXML) 5.0 for Microsoft Office - XSLT Developer's Guide

Operate on Data Values

Suppose a user wants to compare the annual sales figures for each region. Although this information is not hard coded in the source XML document, Sales.xml, you can derive it from the data that is already in Sales.xml. To do this, use the XPath function, sum(),to add the quarterly results for each region.

To calculate total annual sales per region

  1. In your HTML or text editor, open Transform.xsl and delete the following line:
    <!-- Total will go here. -->
  2. Replace the deleted line with the following code:
    <xsl:value-of select="format-number(sum(quarter/@books_sold),'###,###')"/>
  3. Save and close Transform.xsl.

To view the summarized data

  • In Internet Explorer, press F5 to refresh the display of Sales.xml. The Total column now shows the total number of books sold for the year per each region:

How the Function Works

An XPath function takes XPath expressions as its arguments, does something to the input data, and returns the result as a new XPath expression. For more information about XPath functions, see XPath Reference.

The sum(quarter/@books_sold) XPath function takes a node-set, quarter/@books_sold, as input. It then returns the sum of the data values for the books_sold attribute of each <quarter> element in the current context. Here, the current context is the current <region> element, as defined by the XPath expression, //data/region, at the beginning of the outer loop.

As with other programming languages, XSLT supports flow control during the transformation. The next exercise shows how to Control the Flow of Transformation by using conditional statements to compare whether or not each sales region met its sales goal figure.