I create an invoice management system using xml and PHP but the latest PHP version does not support XSLT 2.0 - therefore I have to look for an sum() alternative. How can I transform the valid xslt 2 function "sum(unitprice * quantity)" to xslt 1.0 ?
The XML stuff is based on John's Examples
I tried it with a node-set, but it is not supported "xmlXPathCompOpEval: function node-set not found in"
You can simply create a template sumNumbers that adds the two quantities. Addition can be performed in a select statement:
should work
Actually,
sum(price*quantity)
isn't valid XSLT 2.0 syntax. I guess you mean something like `sum(for $x in * return $x/price*$x/quantity).Summing over a computed value in XSLT 1.0 can be done in the following ways:
two pass solution, create a node-set in which the nodes hold the computed values, then sum over the node-set
recursive solution: write a recursive template that passes the total so far as a parameter, adds sum*quantity for the current node, then recurses to process the remaining nodes
higher-order solution: use Dimitre Novatchev's FXSL library
extension solution: use extension functions like saxon:sum()
In XSLT 1.0 you can use the FXSL's
map()
function/template (and either FXSL'ssum()
function or the standard XPathsum()
) function, as shown in the following example:Having this XML document:
we want to get the sum from all the sales -- this is the sum of the products:
price* quantity * discount1 * discount2 ...* discountN
for each sale.This XSLT 1.0 transformation:
when applied on the above XML document, produces the wanted, correct result:
II. XPath 2.0 solution:
A simplified problem (the originally posted one) can be solved using a simple XPath 2.0 one-liner. If we have this XML document:
then this XPath 2.0 expression:
when evaluated, produces the wanted sum:
Here is an XSLT 2.0 - based verification of this fact:
When this transformation is performed on the XML document above, the wanted, correct result is produced: