Chapter 3. Numbers and Math

Arithmetic is being able to count up to 20 without taking off your shoes.

Mickey Mouse

Introduction

Chapter 2 lamented the absence of sophisticated string-processing facilities in native XSLT 1.0. By comparison, XSLT’s handling of numerical computation is truly “Mickey Mouse”! XSLT 1.0 gives you facilities for basic arithmetic, counting, summing, and formatting numbers, but the remaining mathematics is up to your sheer wit. Fortunately, as with strings, XSLT’s recursive powers permit reasonable mathematical feats with reasonable effort.

In XPath/XSLT 2.0, some of the more obvious math functions have been added including abs(), avg(), max(), min(), round-to-half-even(). Further, there are now more numerical types (xs:integer, xs:double, and the other numeric types defined in XML Schema datatypes) where XSLT 1.0 only had a single floating point numeric type. Thankfully, XPath 2.0 now recognizes scientific notation, whose absence was often a major inconvenience in 1.0.

However, whether you are using 1.0 or 2.0, do not expect to find matrix multiplication or Fast-Fourier transform recipes in this section. If you really need to perform sophisticated math on XML-encoded data, then XSLT is not the language for you. Instead, bring the data into a more mathematically inclined language using an XSLT front-end converter or native SAX or DOM interface. Nevertheless, a web page called “Gallery of Stupid XSL and XSLT Tricks” (http://www.incrementaldevelopment.com/xsltrick ...

Get XSLT Cookbook, 2nd Edition 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.