Reputation: 3516
I am not working with XSLT not too long. I read that variable of XSLT can't be updated on the fly, so how can i do the following task.
I want to sum up Purchase & Sales and put them into a variable, and make some decision according to these values. (For example, if Purchase is greater then sales then do something if not, do something else)
<rows>
<row>
<col attr2="Purchase" >100.00</col>
<col attr2="Sales" >100.00</col>
</row>
<row >
<col attr2="Purchase" >19.16</col>
<col attr2="Sales" >12.94</col>
</row>
<row >
<col attr2="Purchase" >0.67</col>
<col attr2="Sales" >2.74</col>
</row>
<row >
<col attr2="Purchase" >71.95</col>
<col attr2="Sales" >61.54</col>
</row>
<row >
<col attr2="Purchase" >3.62</col>
<col attr2="Sales" >14.72</col>
</row>
<row >
<col attr2="Purchase">8.80</col>
<col attr2="Sales">1.22</col>
</row>
<row >
<col attr2="Purchase" >-4.28</col>
<col attr2="Sales" >6.53</col>
</row>
</rows>
if anyone knows, please help me.
Upvotes: 0
Views: 649
Reputation: 243599
You can calculate the sums as shown in @Eric 's example.
The question you ask in your comment: To calculate the absolute value of x
use the following XPath expression:
(x > 0)*x - not(x > 0)*x
For example:
With the provided XML document,
<xsl:variable name="x" select="(/*/*/col[@attr2='Purchase'])[position()=last()]"/>
<xsl:value-of select="($x > 0)*$x - not($x > 0)*$x"/>
produces:
4.28
Upvotes: 0
Reputation: 97671
XSL variables are more constants: once set, their value cannot be changed. The only way of changing a variable is to use a recursive template, and using a named parameter to hold the current sum.
Or you would, if XSLT didn't have a sum
function!
<xsl:variable name="$purchase-total" select="sum(col[@attr2='Purchase'])" />
<xsl:variable name="$sales-total" select="sum(col[@attr2='Sales'])" />
<xsl:choose>
<xsl:when test="$purchase-total > $sales-total">
<!-- Do something -->
</xsl:when>
<xsl:otherwise>
<!-- Do something -->
</xsl:otherwise>
</xsl:choose>
Upvotes: 1