p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: XSLT Programmer's Reference, 2nd Edition (http://p2p.wrox.com/forumdisplay.php?f=52)
-   -   sum and translate in XPath (http://p2p.wrox.com/showthread.php?t=71722)

nwright December 5th, 2008 05:59 AM

sum and translate in XPath
 
My XML has commas in the numbers so I'm using translate in order to treat as numerical values.
I now need to get the sum of a nodeset and have an issue when attempting to use sum and translate together.

I'm using XPath 1.0

Example XML
<?xml version="1.0" encoding="UTF-8"?>
<items>
    <item>thing one</item>
    <item>thing two</item>
    <value>1,500</value>
    <value>3,700</value>
</items>

The XPath I'm using will never work as sum returns the nodeset and translate only a single item so even if it worked it would only get one item.

Xpath
sum(translate(//value,",",""))

Is there any way to do this or should I run a transform to remove commas?


mhkay December 5th, 2008 06:23 AM

This is easy in XPath 2.0:

sum(//value/number(translate(.,",",""))

It can't be done in pure XPath 1.0 because the argument to sum() has to be a set of nodes; your nodes don't contain numbers, and XPath alone can't create new nodes. You can do it in XSLT 1.0 - one way is to write a recursive template that processes the nodes one by one, adding to a running total as it goes; another way is a two-pass approach where you construct a new tree containing the translated nodes. But 2.0 is much easier.

Michael Kay
http://www.saxonica.com/
Author, XSLT 2.0 and XPath 2.0 Programmer's Reference

nwright December 5th, 2008 08:20 AM

Thanks for your assistance, unfortunatly I am restricted to using 1.0 for the time being.




All times are GMT -4. The time now is 02:54 PM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.