O'Reilly logo

XML Hacks by Michael Fitzgerald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Perform Math with XSLT

XPath 1.0 offers a number of math operations that can be performed within expressions.

With the help of XPath, XSLT can perform a number of math operations within expressions. Expressions can occur within the value of a select attribute. You can perform addition, subtraction, multiplication, division, and modulo operations. There are also a number of XPath functions that perform math, such as count(), ceiling(), floor(), number( ), round(), and sum().

Consider the following XML representation of a spreadsheet, worksheet.xml , with numbers arranged in columns and rows (Example 3-42).

Example 3-42. worksheet.xml

<?xml version="1.0" encoding="UTF-8"?>
   
<worksheet>
 <column>
  <row>12</row>
  <row>199</row>
  <row>72</row>
  <row>29</row>
 </column>
 <column>
  <row>5</row>
  <row>783</row>
  <row>43</row>
  <row>1432</row>
 </column>
 <column>
  <row>2</row>
  <row>429</row>
  <row>598</row>
  <row>56</row>
 </column>
</worksheet>

Using simple addition, the stylesheet sums.xsl (Example 3-43) sums the values in worksheet.xml first by rows, then by columns.

Example 3-43. sums.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" encoding="UTF-8" indent="yes"/> <xsl:template match="worksheet"> <sums> <sum> <row1> <xsl:value-of select="column[1]/row[1] + column[2]/row[1] + column[3]/row[1]"/> </row1> <row2> <xsl:value-of select="column[1]/row[2] + column[2]/row[2] + column[3]/row[2]"/> </row2> <row3> <xsl:value-of select="column[1]/row[3] + ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required