I can use SUM(xpath) to sum all node values, but I also have a requirement to sum all positive node values, all negative node values and all node values treating them as absolute values. Is this possible with XSLT?
Asked
Active
Viewed 1,485 times
2 Answers
3
To sum all the positive node values, you can do:
<xsl:value-of select="sum(//*[. > 0])" />
To sum all the negative node values, you can do:
<xsl:value-of select="sum(//*[. < 0])" />
To sum the absolute values of the numbers, you can do:
<xsl:value-of select="sum(//*[. > 0]) - sum(//*[. < 0])" />

Frédéric Hamidi
- 258,201
- 41
- 486
- 479
-
3Wrong. sum(-//x) gives a type error in XSLT 2.0 because unary minus can only be applied to a singleton; in XSLT 1.0 it ignores all but the first node in the node-set, which destroys the purpose. – Michael Kay Jan 13 '12 at 22:19
-
Thanks for the heads-up, it worked in the online tester I used but the negative number could have been the first node in the set, I don't remember. Applying unary minus to the value returned by `sum()` should fix this. XSLT 2.0 also has an `abs()` function that can be used instead of my last code snippet. – Frédéric Hamidi Jan 13 '12 at 22:26
-
FWIW, switching the operands and using binary instead of unary minus is even more readable. – Frédéric Hamidi Jan 13 '12 at 23:24