Reputation: 602
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 ?
Upvotes: 0
Views: 714
Reputation: 15361
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.
Upvotes: 1