0

I want to sum all the values that meet my condition (see below). In case the condition is not met, I want to return 0. Please see my below code and advise. Currently it is returning empty .

Condition : sum all values if fieldlabel = 'A', if not retuen (in this example need to return 30) Let s suppose i am looking for 'C'instead of 'A', in this case i have to return 0

Example file :

<root>
<parent>
<element>
<elementname>A</elementname>
<elementvalue>10</elementvalue>
</element>
<element>
<elementname>B</elementname>
<elementvalue>20</elementvalue>
</element>
<element>
<elementname>A</elementname>
<elementvalue>30</elementvalue>
</element>
</parent>
</root>

Code :

<xsl:template match="/">
    <xsl:for-each select="/root/parent/element">
      <xsl:variable name="field">
        <xsl:value-of select="elementname" />
      </xsl:variable>
      <xsl:if test="$field='A'">
        <xsl:value-of select="sum(elementvalue)" />
      </xsl:if>    
    </xsl:for-each>

 <xsl:variable name="finalresult">
        <xsl:choose>
                 <xsl:when test="$fieldname = '' ">0</xsl:when>
                 <xsl:otherwise><xsl:value-of select="$field"/>
</xsl:otherwise>
           </xsl:choose>
     </xsl:variable> 

1 Answer 1

2

When you match /root/parent/element in your xsl:for-each and you sum(elementvalue), you're only summing the elementvalue of the current element and there's only ever one of those.

Instead, consider testing the condition in a predicate:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes" omit-xml-declaration="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="field" select="'A'"/>

  <xsl:template match="root/parent">
    <xsl:value-of select="sum(element[elementname=$field]/elementvalue)"/>
  </xsl:template>

</xsl:stylesheet>

Fiddle: http://xsltfiddle.liberty-development.net/jyyiVhA

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.