Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handel empty elements during doing sum of elements using xslt

Tags:

xml

xslt

<LIST_R7P1_1>
 <R7P1_1> 
 <ORIG_EXP_PRE_CONV /> 
  <EXP_AFT_CONV >34<EXP_AFT_CONV />
  <GUARANTEE_AMOUNT /> 
  <CREDIT_DER /> 
 </R7P1_1>
</LIST_R7P1_1>


<total><xsl:value-of select="LIST_R7P1_1/R7P1_1/ORIG_EXP_PRE_CONV + LIST_R7P1_1/R7P1_1/EXP_AFT_CONV + LIST_R7P1_1/R7P1_1/GUARANTEE_AMOUNT + LIST_R7P1_1/R7P1_1/CREDIT_DER"/></total>

In total i am getting null value because of the empty elements like <CREDIT_DER />, <ORIG_EXP_PRE_CONV /> etc .

How to handle that so that I can get a Numeric value

Please suggest

like image 768
user429727 Avatar asked Aug 25 '10 07:08

user429727


2 Answers

Here is a small example where the trick in the answer of @DevNull will not help:

<a>
 <b>5</b>
 <c>
  <d></d>
  <e>1</e>
  <f>2</f>
 </c>
</a>

We want: /a/c/d + /a/c/f

To guarantee that we get the sum, although some of these may be empty or not numbers, use:

sum((/a/c/d|/a/c/f)[number(.) = number(.)])

Explanation:

The XPath expression: (/a/c/d|/a/c/f)[number(.) = number(.)]

selects only those of all united nodes, whose value is a number. Therefore, the sum() function will be provided only with numeric arguments and will not produce NaN.

The expression number(.) = number(.) is true only when . is a number.

Here we use that number(somethingNon-Number) is NaN

and that NaN isn't equal to anything, even to NaN.

like image 116
Dimitre Novatchev Avatar answered Oct 06 '22 02:10

Dimitre Novatchev


<total><xsl:value-of select="sum(/LIST_R7P1_1/R7P1_1/*/text())"/></total>

You also need to fix your XML (the EXP_AFT_CONV end tag):

<LIST_R7P1_1>
  <R7P1_1>
    <ORIG_EXP_PRE_CONV/>
    <EXP_AFT_CONV>34</EXP_AFT_CONV>
    <GUARANTEE_AMOUNT/>
    <CREDIT_DER/>
  </R7P1_1>
</LIST_R7P1_1>
like image 30
Daniel Haley Avatar answered Oct 06 '22 01:10

Daniel Haley