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] + ...

Get XML Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.