user1503496
user1503496

Reputation: 191

displaying value if element not empty

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> 

Upvotes: 0

Views: 48

Answers (1)

Daniel Haley
Daniel Haley

Reputation: 52878

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

Upvotes: 2

Related Questions