xsl-list
[Top] [All Lists]

Re: Recursive sums in xslt 1.0

2005-03-13 15:32:20

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
________________________________________________________________________

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--



<Prev in Thread] Current Thread [Next in Thread>