How to pass empty elements at runtime with a sum of elements using 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> 

As a result, I get a null value due to empty elements such as <CREDIT_DER />, <ORIG_EXP_PRE_CONV /> etc.

How to handle this to get a numerical value

Please suggest

+4
source share
2 answers

Here is a small example where the trick in @DevNull's answer doesn't 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 ensure that we receive the amount, although some of them may be empty or not contain numbers, use :

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

Explanation

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

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

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

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

and that NaN not equal to anything, even before NaN .

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

You also need to fix your XML ( 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> 
+2
source

All Articles