Click to See Complete Forum and Search --> : XSL Variable within for-each


mjs80
12-08-2009, 06:51 PM
Hi I am fairly new to XML/XSL and have tried searching around for what I am looking for with no success. Basically I have created a variable that is creating a sub total for each product on an invoice (this works). I then need to calculate and output the overall total price, this needs to be output outside of the for-each...but if I do this I get an undefined variable error. I understand the for-each is a child node meaning that the $subtotal variable is not global. could you point me in the right direction here. thanks

<xsl:for-each select="DeliveryDetails/ProductOrder">
<tr align="center">
<td width="150"><xsl:value-of select="Description" /></td>
<td width="150"><xsl:value-of select="ReferenceNo" /></td>
<td width="100"><xsl:value-of select="Quantity" /></td>
<td width="100">£<xsl:value-of select="Price" /></td>
<td width="100">£ <xsl:variable name="subtotal" select="Quantity*Price" /><xsl:value-of select="$subtotal" /></td>
</tr>
</xsl:for-each>

<xsl:value-of select="count($subtotal)"/>

rnd me
12-17-2009, 12:12 AM
you can only set the value of a variable once.

mjs80
12-17-2009, 10:28 AM
I understand that, but I don't think I am trying to set the value of the variable again, I am just trying to catch the value of that variable through each loop, therefore adding the total price through each loop. would I need to create a new variable first? but then that goes against changing the value of it, because the value would change each time? I am not sure if there is actually a way around this!

rnd me
12-17-2009, 04:01 PM
I understand that, but I don't think I am trying to set the value of the variable again, I am just trying to catch the value of that variable through each loop, therefore adding the total price through each loop.

well adding would change the value wouldn't it?


there is a sum function in xslt:


<xsl:value-of select="sum(DeliveryDetails/ProductOrder//Quantity) + sum(DeliveryDetails/ProductOrder//Price) "/>

mjs80
12-20-2009, 04:26 AM
Thanks for the reply. The code you sent would not work because the quantity needs to be multiplied by the price on each line. therefore I have tried:
select="sum(Quantity*Price)" />

I thought this might work out what's in the brackets and then total it up...however this does not work. I tried your suggestion however this would not work because the price for each product is different meaning I cannot add the quantity then add the price to get the total.