Skip to Main Content
XML Hacks
book

XML Hacks

by Michael Fitzgerald
July 2004
Intermediate to advanced content levelIntermediate to advanced
479 pages
12h 30m
English
O'Reilly Media, Inc.
Content preview from XML Hacks

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] + ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

XML Schema Complete Reference, The

XML Schema Complete Reference, The

Cliff Binstock, Chris Galtenberg, Mike Wooding, Chris Dix, Mitchell Smith, Dave Peterson
.NET & XML

.NET & XML

Niel M. Bornstein

Publisher Resources

ISBN: 0596007116Supplemental ContentErrata Page