[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

Re: [xsl] Recursive sums in xslt 1.0


Subject: Re: [xsl] Recursive sums in xslt 1.0
From: David Carlisle <davidc@xxxxxxxxx>
Date: Sun, 13 Mar 2005 22:32:20 GMT

> I understand the named template, of course. I don't understand the 
> second sentence, though. How would this work? I'm raising the question 
> here rather than privately, because it seems like an important technique 
> that might be useful (and difficult) for others like myself you are 
> (now) probably more than beginners but less than experts.

If you are doing a lot of this sort of thing, look at Dimitre's FXSL
library (google for the exact address) however if you have  set of nodes
$x and the idea is to first transformeah node by calling a named
template "foo" (which can do anything eg return 0 for nodes that you
want to ignore) and sum teh results returned by those templates you have
(at least) two choices.

If you have access to a node-set extension you can do the
transform first:
<xsl:variable name="y">
<xsl:for-each select="$x">
 <x><xsl:call-template name="foo"/></x>
</xsl:for-each>
</xsl:variable>
then sum:
<xsl:value-of select="sum(x:node-set($x)/x)"/>

if you haven't got node-set or if you have lots of items and don't want
to store the intermediate set of element nodes storing the transformed
items then you can process them ne at a time adding up as you go, eg

<xsl:template name="sum">
 <xsl:param name="items" select="$x"/>
 <xsl:param name="sum" select="0"/>
 <xsl:variable name="t">
  <xsl:for-each select="$items[1]"/>
  <xsl:call-template name="foo"/>
  </xsl:for-each>
 </xsl:variable>
 <xsl:choose>
 <xsl:when test="count($items)=1">
  <xsl:value-of select="$sum + $t"/>
 </xsl:when>
 <xsl:otherwise>
  <xsl:call-template name="sum">
   <xsl:with-param name="items" select="$x[position()!=1]"/>
   <xsl:with-param name="sum" select="$sum + $t"/>
 </xsl:otherwise>
 </xsl:choose>
</xsl:template>

(untested) 

David

________________________________________________________________________
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________


Current Thread