1

How to calculate the sum of the XML element numbers with XSLT 1.0?
I have tried select="sum(str:tokenize(., ',')) , unfortunatelly i did not get result.

<numbers>8,8,0,0,0,0,0</numbers> = 16

xml

<documents>
<document>
  <userData>
    <userInfo>
      <user>John</user> 
      <id>1000</id> 
      <date1>10.01.2010</date1> 
      <date2>31.12.2019</date2> 
      <weight>1</weight> 
      <numbers>0,0,0,0,0,0,0</numbers> 
    </userInfo>
    <userInfo>
      <user>Susan</user> 
      <id>1001</id> 
      <date1>01.01.2015</date1> 
      <date2 /> 
      <weight>0.4</weight> 
      <numbers>8,8,0,0,0,0,0</numbers>  
    </userInfo>
  </userData>
</document>
</documents>
ottrin
  • 35
  • 5
  • 2
    Not all XSLT processors support the `str:tokenize()` extension function. Which processor are you using? – michael.hor257k Jan 19 '20 at 12:40
  • Sorry, I do not know. I write XSLT for one ERP printout. I'm so green. – ottrin Jan 19 '20 at 15:34
  • 1
    Find out - see here how: https://stackoverflow.com/a/25245033/3016153 P.S. If you don't know which processor you use, how do you know the XSLT version needs to be1.0? – michael.hor257k Jan 19 '20 at 17:32
  • I know I must use XSL version 1.0. I mainly copy some earlier XSL and add some basic if, choose, for, sum, etc functions and design it. – ottrin Jan 20 '20 at 19:35

1 Answers1

2

Try this:

   <xsl:template match="numbers">
        <xsl:copy>
            <xsl:call-template name="sum">
                <xsl:with-param name="text" select="."/>
                <xsl:with-param name="currentsum" select="0"/>
            </xsl:call-template>
        </xsl:copy>
    </xsl:template>

    <xsl:template name="sum">
        <xsl:param name="text"/>
        <xsl:param name="currentsum"/>
        <xsl:choose>
            <xsl:when test="contains($text, ',')">
                <xsl:variable name="sum" select="number($currentsum) + number(substring-before($text, ','))"/>
                <xsl:call-template name="sum">
                    <xsl:with-param name="text" select="substring-after($text, ',')"/>
                    <xsl:with-param name="currentsum" select="$sum"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="number($currentsum) + number($text)"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

See transformation at https://xsltfiddle.liberty-development.net/3NSTbeK

Rupesh_Kr
  • 3,395
  • 2
  • 17
  • 32