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 the trick.

Example 5-4. 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>
      <xsl:apply-templates/>
    </body>
  </html>
</xsl:template>

<xsl:template match="item">
  <p><b>Item:</b> <xsl:value-of select="@name"/>
  Orig. Price: <xsl:value-of select="@price"/>, Our Price:
  <xsl:value-of select="@price * 0.8"/>
  </p>
</xsl:template>

</xsl:stylesheet>

The XPath numerical expressions are in the xsl:value-of elements. The discount is achieved by multiplying the value of the price attribute by 0.8. You can run the transformation using the 4xslt tool illustrated in the previous chapter:

$ 4xslt.bat products.xml products.xsl
<html>
  <body>
    <p>
      <b>Item: </b>bowl
  Orig. Price: 19.95, Our Price: 15.96</p>
    <p>
      <b>Item: </b>spatula
  Orig. Price: 4.95, Our Price: 3.96</p>
    <p>
      <b>Item: </b>power mixer
  Orig. Price: 149.95, Our Price: 119.96</p>
    <p>
      <b>Item: </b>chef hat
  Orig. Price: 39.95, Our Price: 31.96</p>
  </body>
</html>

The div and mod operators work as the others do. For example, @price div 2 divides all prices designated by 2.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.125.51