'xslt, calculating sum of sum using function
I have client invoices which I calculate price* quantity + total for this colum (for each invoice and each client) using the following function: Total
<xsl:template name="sumProducts">
<xsl:param name="pList"/>
<xsl:param name="pRunningTotal" select="0"/>
<xsl:choose>
<xsl:when test="$pList">
<xsl:variable name="varMapPath" select="$pList[1]"/>
<xsl:call-template name="sumProducts">
<xsl:with-param name="pList" select="$pList[position() > 1]"/>
<xsl:with-param name="pRunningTotal" select="$pRunningTotal + $varMapPath/unitprice * $varMapPath/quantity"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
$<xsl:value-of select="format-number($pRunningTotal, '#,##0.00')"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
I would like to calculate the total for all invoices per client and total invoices for all clients.
Thank you
Solution 1:[1]
Instead of using recursive template I would use a variable. Take a look at this example where I calculate subtotal for each item and add it to the item. Then I use sum() function for calculating total:
Input xml:
<root>
<items>
<item price="19" quantity="12" />
<item price="5" quantity="3" />
<item price="4" quantity="1" />
<item price="2" quantity="2" />
</items>
</root>
Xslt:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="items">
<root>
<xsl:variable name="items-with-sub-totals">
<xsl:for-each select="item">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="sub-total">
<xsl:value-of select="@price * @quantity"/>
</xsl:attribute>
</xsl:copy>
</xsl:for-each>
</xsl:variable>
<debug>
<xsl:copy-of select="msxsl:node-set($items-with-sub-totals)/*"/>
</debug>
<xsl:value-of select="concat('Total:', sum(msxsl:node-set($items-with-sub-totals)/item/@sub-total))" />
</root>
</xsl:template>
</xsl:stylesheet>
Output (I added some debug information to show how the variable looks like):
<?xml version="1.0" encoding="utf-8"?>
<root>
<debug>
<item price="19" quantity="12" sub-total="228" />
<item price="5" quantity="3" sub-total="15" />
<item price="4" quantity="1" sub-total="4" />
<item price="2" quantity="2" sub-total="4" />
</debug>
Total:251
</root>
This is a bit different approach than you are trying but hopefully will work for you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pawel |
