Reputation: 305
I want to evaluate the content of a string variable as a operation.
My variable it's this string: 1+1+0
I want to make the operation and get the value 2.
Thanks in advance, Gustavo
Upvotes: 0
Views: 147
Reputation: 163595
There's no general mechanism in XSLT 1.0 or XSLT 2.0 to evaluate an XPath expression supplied as a string value. Many products have an extension to do this (see for example saxon:evaluate()). A general mechanism is being introduced in XSLT 3.0: the xsl:evaluate instruction.
Upvotes: 1
Reputation: 3696
In XSLT 2.0 this can be done by using tokenize()
, number()
and sum()
functions, for example the below. Note that I included possible whitespaces surrounding the +
signs.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:variable name="test1">1+1+0</xsl:variable>
<xsl:variable name="test2"> 3 +
5 + 12 </xsl:variable>
<xsl:template match="/">
<xsl:variable name="testSplit1" select="tokenize($test1,'\s*\+\s*')"/>
<xsl:variable name="testSplitNum1">
<xsl:for-each select="$testSplit1">
<item><xsl:value-of select="number(.)"/></item>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="testSplit2" select="tokenize($test2,'\s*\+\s*')"/>
<xsl:variable name="testSplitNum2">
<xsl:for-each select="$testSplit2">
<item><xsl:value-of select="number(.)"/></item>
</xsl:for-each>
</xsl:variable>
<root>
<items1><xsl:copy-of select="$testSplitNum1"/></items1>
<sum1><xsl:value-of select="sum($testSplitNum1/item)"/></sum1>
<items2><xsl:copy-of select="$testSplitNum2"/></items2>
<sum2><xsl:value-of select="sum($testSplitNum2/item)"/></sum2>
</root>
</xsl:template>
</xsl:stylesheet>
The result (with dummy input file) is
<?xml version="1.0" encoding="UTF-8"?>
<root>
<items1>
<item>1</item>
<item>1</item>
<item>0</item>
</items1>
<sum1>2</sum1>
<items2>
<item>3</item>
<item>5</item>
<item>12</item>
</items2>
<sum2>20</sum2>
</root>
Upvotes: 0