Tuesday, April 10, 2012

XSLT template to sum derived values in a nodeset

Here is a XSLT 1.0 template to find the sum of a set of multiplication results from a node set. In my case, price and quantity are the available nodes in XML. 'orderTotal' (name of the template below) needs to multiply price by quantity for all nodes in a nodeset and total the derived values to find the grand total.

i.e.: orderTotal= sum(//*/price X //*/quantity)


Template

  <xsl:template name="orderTotal">
   <xsl:param name="nodes"/>
   <xsl:param name="total" select="0"/>
 
   <xsl:if test="$nodes[1]">
     <xsl:call-template name="orderTotal">
       <xsl:with-param name="nodes" select="$nodes[position() &gt; 1]"/>
       <xsl:with-param name="total" select="$total + $nodes[1]/k:price * $nodes[1]/k:quantity"/>
     </xsl:call-template>
   </xsl:if>

   <xsl:if test="not($nodes[1])">
     <xsl:value-of select="$total"/>
   </xsl:if>

 </xsl:template>

No comments:

Post a Comment