On 10/9/06, Nuno Viana (Gmail)
<nuno(_dot_)carlos(_dot_)viana(_at_)gmail(_dot_)com> wrote:
Hi everybody,
I have the following XML file, which represents expressions with "+" and "*"
artihmentic operands:
<m value="10">
<i value="5"/>
<m value="10">
<i value="2"/>
<i value="2"/>
<i value="2"/>
</m>
</m>
This represents the following expression:
10 * (5 + (10 * (2 + 2 + 2)))
I want to compute the expression's value (for the given example, the
result should be 650).
Can anyone help me achieve this through a single recursive template?
I think you are better off with two templates:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="m">
<xsl:variable name="sum">
<xsl:apply-templates select="*[1]"/>
</xsl:variable>
<xsl:choose>
<xsl:when test="$sum != ''">
<xsl:value-of select="@value * $sum"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="@value"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="i">
<xsl:variable name="sum">
<xsl:apply-templates select="following-sibling::*[1]"/>
</xsl:variable>
<xsl:choose>
<xsl:when test="$sum != ''">
<xsl:value-of select="@value + $sum"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="@value"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
If you are using XSLT 2.0 then you can drop the choose/when for the
more terse if then else:
select="if ($sum != '') then (@value + $sum) else (@value)"
cheers
andrew
--~------------------------------------------------------------------
XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--