XPath Arithmetic Operators
In addition to selecting elements by location paths, XPath also provides capability for data manipulation. The numerical parts of an XML document can be added, divided, subtracted, and multiplied. Likewise, strings can be compared for equality.
XPath provides arithmetic operators for use within XPath
expressions. This capability comes in very handy in XSL transformations
that involve totaling an item list or applying discounts to product
prices for display in HTML. The operators available in XPath are
+
, -
, *
,
div
, and mod
(addition, subtraction, multiplication,
division, and modulus, respectively.) There are also functions such as
sum
that allow you to total sets of
numbers and perform other tasks. We cover functions in the next
section.
Imagine that you have an XML file containing a list of products, and you want to display these products in another application (such as your web site) but need to apply a 20% discount to all retail prices. You can use the XPath arithmetic operators to solve this problem. Let’s turn to the source XML document (products.xml) shown in Example 5-3.
Example 5-3. products.xml
<?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>
To apply a blanket 20% discount to all products, you can use XPath
from within an XSLT document. The XSLT shown in Example 5-4 (products.xsl )
does ...
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.