Re: [xsl] A more concise way to handle empty numeric elements

Subject: Re: [xsl] A more concise way to handle empty numeric elements
From: Martin Honnen <Martin.Honnen@xxxxxx>
Date: Thu, 07 Jun 2007 15:17:36 +0200
Mark Anderson wrote:

I have to process an XML file that contains a lot of numeric data. Many of the elements that have no value are empty instead of being zero and it may differ for each line, for example

<line id=1>
            <cost1>1000</cost1>
            <cost2>0</cost2> <!-- 0 here, but empty in next line -->
            <cost3></cost3>
</line>
<line id=2>
            <cost1>2000</cost1>
            <cost2></cost2>
            <cost3>3000</cost3>
</line>

I want to do:

<xsl:for-each select="line">
       <xsl:value-of select="format-number(cost1 + cost2 + cost3,'#,###')"/>
      </xsl:for-each>

However, the empty elements will cause "NaN" to be displayed

Can't you simply do <xsl:value-of select="format-number(sum(*[text()]),'#,###')"/> That way only elements which have a text content are summed up.

If you have other child elements than cost1, cost2, cost3 then you could do

<xsl:value-of select="format-number(sum(*[text() and (self::cost1 or self::cost2 or self::cost3)]),'#,###')"/>

--

	Martin Honnen
	http://JavaScript.FAQTs.com/

Current Thread