Skip to Main Content
Python & XML
book

Python & XML

by Christopher A. Jones, Fred L. Drake
December 2001
Intermediate to advanced content levelIntermediate to advanced
380 pages
11h 54m
English
O'Reilly Media, Inc.
Content preview from Python & XML

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"> ...
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 Processing with Python

XML Processing with Python

Sean McGrath
Python One-Liners

Python One-Liners

Christian Mayer

Publisher Resources

ISBN: 0596001282Supplemental ContentErrata Page