tags:

views:

200

answers:

1

Say I have an Xml fragment that I am walking through with XSL:

<Columns>
   <Column width="100">
   <Column width="50">
   <Column width="75">
   <Column width="33">
</Columns>

Basically what I want to do is, as I am walking through each node, I need to store a sum of the previous 'width' attributes to be used for the current Column node. For example, when I reach the last Column node (with width 33), I would like to have access to the sum of the all the previous widths in a variable of some kind (100+50+75). I know that values of variables cannot be changed once set in XSL, so I'm wondering if there is some way using template params or something to do this. Thanks in advance!

+1  A: 

Essentially you take advantage of template recursion and limit the set being passed to the next sibling only. Starting with the first item then you can continually pass in updated values to the next template call.

<xsl:template match="/">
    <xsl:apply-templates select="Columns/Column[1]" />
</xsl:template>

<xsl:template match="Column">
    <xsl:param name="runningtotal" select="0"/>
    [<xsl:value-of select="@width"/>:<xsl:value-of select="$runningtotal+@width"/>]
    <xsl:apply-templates select="following-sibling::Column[1]" >
     <xsl:with-param name="runningtotal" select="$runningtotal+@width"/>
    </xsl:apply-templates>
</xsl:template>
annakata
I think this is going to work for me but I guess I'm just a little confused on where this fits in the context of a for-each statement. Do I call <xsl:apply-templates select="Columns/Column[1]" /> within the for-each statement? I'm guessing no.... basically when walking through the Column nodes in the 'for-each', I want to print the current $runningtotal var
Nate
Ah ok I get it now...it's sort of in place of a 'for-each'. Thank you very much!
Nate
exactly so - templates are *considerably* more powerful than for-each, and the more XSL way of doing things. It's a more difficult concept to learn coming from a non-functional programming background I think, but you should ideally favour apply-templates > call-template > for-each. Jeni T has a ood discussion on this: http://www.jenitennison.com/blog/node/9
annakata