4

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?

Shane
  • 157
  • 2
  • 10

2 Answers2

3

To sum all the positive node values, you can do:

<xsl:value-of select="sum(//*[. &gt; 0])" />

To sum all the negative node values, you can do:

<xsl:value-of select="sum(//*[. &lt; 0])" />

To sum the absolute values of the numbers, you can do:

<xsl:value-of select="sum(//*[. &gt; 0]) - sum(//*[. &lt; 0])" />
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • 3
    Wrong. 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
2

Please see

xslt 1 and sum function

for a list of general approaches to the problem

Community
  • 1
  • 1
Michael Kay
  • 156,231
  • 11
  • 92
  • 164