I have a few items like this one:
<item type="goods">
<quantity unit="pcs">172</quantity>
<unit-price currency="PLN">420</unit-price>
<VAT>7</VAT>
</item>
I want to print sum of the cost of this items. So what mathematically:
sum(quantity*unit-price)
How can I do that with xsl? I've tried using variables with for-each loop inside and normal valye-of. but I'm still getting some strange results (I won't add this code since it's just bad).
XSLT:
Input XML:
Output:
In addition to the correct answer by Kirill:
I. XPath 2.0 (XSLT 2.0) solution:
Use this single XPath 2.0 expression from any language hosting XPath 2.0:
Here is a complete example using XSLT 2.0 as the host of XPath 2.0:
when applied on the following XML document:
the wanted, correct result is produced:
II. XSLT 1.0 solution using the
transform-and-sum
template/function of FXSL 1.xwhen this transformation is applied on the same XML document (above), the same correct result is produced:
Do note: Using FXSL one doesn't need to implement explicit recursion "for the Nth time", the solution is compact and potential errors writing the recursion are eliminated altogether.
As a whole the total development time, readability and flexibility are dramatically improved.