Adding of two variables in xslt within choose statement
<xsl:choose>
<xsl:when test="$cty='LOHNSTD'">
<xsl:variable name="sum" select="$sum + $amt"/>
</xsl:when>
<xsl:when test="$cty='REGPAY'">
<xsl:variable name="sum1">
<xsl:value-of select="$sum1 + $amt"/>
</xsl:variable>
</xsl:when>
</xsl:choose>
In the above code it gives me warning mes开发者_C百科sage saying variables sum and sum1 are not declared. amt and cty are parameters being passed to this template. Can any one help me in doing the summation based on different category codes?
As already mentioned, you have two problems with your stylesheet fragment: ussing an undeclare variable reference (xsl:variable name="sum" select="$sum + $amt"
), and loosing the variable scope outside the xsl:when
.
If you want to declare a variable with value deppending on some conditions, then the answer from Ledhund is the right choise: use xsl:choose
inside variable's content template.
Also, if the terms of sum are node sets, you could use this expression:
sum($A|$B[$cty='LOHNSTD']|$C[$cty='REGPAY'])
Or
$A + $B[$cty='LOHNSTD'] + $C[$cty='REGPAY']
If you are trying to chance the value of an already declared variable, then you should refactor your transformation because that's not posible in any declarative paradigm as XSLT.
If you can live without having two sum-variables I'd do it like this
<xsl:variable name="sum">
<xsl:choose>
<xsl:when test="$cty='LOHNSTD'">
<xsl:value-of select="$something + $amt"/>
</xsl:when>
<xsl:when test="$cty='REGPAY'">
<xsl:value-of select="$something_else + $amt"/>
</xsl:when>
</xsl:choose>
</xsl:variable>
However if the main thing is to increase the value of variables depending on some condition, you can't. Variables are fixed.
First, you cannot declare a variable inside a choose
construct and use it elsewhere. A variable with no following sibling instructions is useless.
In your example you have two problems, the one mentioned above, and that you're trying to use the variables $sum
and $sum1
before they're declared (just as the error message suggests). Essensially, you're trying to calculate a sum using the variable you are declaring.
I'm not sure what you're trying to accomplish, but if you give us some more information regarding the problem I'm sure we can help you with a better solution to it.
精彩评论