Similar to this question (http://stackoverflow.com/q/1333558/948404) I want to use XPath to calculate a sum over products in a structure like this:
1.0
3
2.5
2
Is there an XPath expression that calculates the sum of the products of each items value and quantity?
Update: The solution has to work with PHPs XSLTProcessor class meaning that it probably has to be XSLT 1.0 compliant. This is why I did not yet accept the two probably correct answers using XSLT 2.0. I could neither test them in my PHP implementation nor in my browser nor in the Tryit Editor [1] from w3schools. Sorry!
解决方案
Use this XPath 2.0 expression:
sum(/items/item/(value * quantity))
Here is an XSLT 2.0 transformation as verification:
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
When this transformation is applied on the provided XML document:
1.0
3
2.5
2
the XPath expression is evaluated and the result of this evaluation is output:
8
Explanation:
In XPath 2.0 it is legal for a location step to be
/(expression),
or even
/someFunction(argumentList)
II. XSLT 1.0 solution:
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
"$pAccum + $pNodes[1]/value * $pNodes[1]/quantity"/>
when this transformation is applied on the provided XML document (above), again the wanted, correct result is produced:
8
Do note: Such kind of problems are easy to solve using the