Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT 1.0 adding values together from multiple nodes

Tags:

xslt

xslt-1.0

Say I have the following XML

    <A>100</A>
    <B>200</B>
    <C>300</C>

and the following XSLT

  <TEST>
    <xsl:value-of select="A + B + C"/>
  </TEST>

It produces the following output

<TEST>600</TEST>

however, when one of the nodes is blank

    <A></A>
    <B>200</B>
    <C>300</C>

I get the following.

<TEST>NaN</TEST>

I only want to add the nodes that are valid numbers. I could do this if xsl allowed me to dynamically replace a variable value by adding to the already existing variable, but even that would be messy. I assume there is an easy way that I'm missing?

I want XSLT 1.0 answers only please.

Thanks!

like image 413
james31rock Avatar asked Sep 04 '12 19:09

james31rock


1 Answers

  <TEST>
    <xsl:value-of select="sum((A | B | C)[number(.) = .])"/>
  </TEST>

That is, sum the subset of the elements A,B,C consisting of those whose contents can be used as numbers.

Note that number('') yields NaN, and (NaN = NaN) is false, so this will not include elements without text content.

We test for numbers as discussed at https://stackoverflow.com/a/3854389/423105

like image 178
LarsH Avatar answered Nov 18 '22 07:11

LarsH