XPath Functions

XPath provides numerous functions for working with numbers and strings, and allows you to complete transformations and mine XML data without having to constantly bridge other APIs or technologies to do simple string and arithmetic operations. Adding, simple division, multiplication, and string searching are available as built-in functions of XPath.

Working with Numbers

Several XPath functions are available to you. In Example 5-4, multiplication is used to apply a 20% discount to products. If you need to total a list of products, you can use the sum function, working with the same products data again:

<?xml version="1.0" encoding="UTF-8"?>
<products>
        <item name="bowl" price="19.95"/>
        <item name="spatula" price="4.95"/>
        <item name="power mixer" price="149.95"/>
        <item name="chef hat" price="39.95"/>
</products>

This time, in Example 5-5, you can use a single XPath expression to generate a total. The expression sum(//@price) returns the sum of the values of all price elements in the products document. Now go back and modify the stylesheet you created to discount the products, but this time add in an xsl:value-of element to generate a total.

Example 5-5. products.xsl

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
    <body>
      <table>
        <xsl:apply-templates/>
      </table>
      <p>Your Total:
         <xsl:value-of select="sum(//@price)"/> </p> </body> </html> </xsl:template> <xsl:template match="item"> ...

Get Python & XML 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.