0

I have this simple string stored in a variable :

<xsl:variable name="equation">
    15+10+32+98 
</xsl:variable>

and i want for xsl to take the string stored in this variable and deal with as a math equation to get the result, is there any suggestions ?

zerzer
  • 613
  • 2
  • 8
  • 20
  • Similar to [this question](http://stackoverflow.com/questions/10046104/xsl-evaluate-expression). – nwellnhof Jan 11 '14 at 16:17
  • @nwellnhof i get this : 'evaluate' is not a valid object reference. i've included dyn namespace – zerzer Jan 11 '14 at 16:27
  • I think you need to give more details: What version of XSLT? What XSLT processor(s)? What kind of calculations do you want to perform? It seems you don't have equations (i.e. something like `a^2+b^2=c^2`) but only terms with actual numbers and no symbols, right? What operations do you have? Do you have brackets? Do you need to support correct operator precedence? – Thomas W Jan 11 '14 at 16:57
  • @ThomasW thanks for your interest , i just need to do simple adition without any brackets or nothing just a+b+c .... i am using xsl 1.0 and using javax.xml.transform found in this link : http://stackoverflow.com/questions/19811581/how-to-convert-xml-to-html-using-xslt-in-java – zerzer Jan 11 '14 at 17:00

1 Answers1

1

If you only have to sum up numbers, the following XSLT 1.0 template add takes a "plus separated string" as argument and returns the sum.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="text"/>

  <xsl:template name="add">
    <xsl:param name="plusSeparatedString"/>
    <xsl:param name="sumValue" select="0"/>

    <xsl:choose>
      <xsl:when test="contains($plusSeparatedString,'+')">
        <xsl:call-template name="add">
          <xsl:with-param name="plusSeparatedString" select="substring-after($plusSeparatedString,'+')"/>
          <xsl:with-param name="sumValue" select="$sumValue + substring-before($plusSeparatedString,'+')"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:copy-of select="$sumValue + $plusSeparatedString"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="/">
    <xsl:call-template name="add">
      <xsl:with-param name="plusSeparatedString" select="'4 + 6+ 8'"/>
    </xsl:call-template>
  </xsl:template>
</xsl:stylesheet>

Apply this test stylesheet to any document (e.g. itself) to see it works.

Thomas W
  • 14,757
  • 6
  • 48
  • 67