Re: [xsl] [XSLT]: Recursive Function to Add/Multiply

Subject: Re: [xsl] [XSLT]: Recursive Function to Add/Multiply
From: "Andrew Welch" <andrew.j.welch@xxxxxxxxx>
Date: Mon, 9 Oct 2006 09:53:01 +0100
On 10/9/06, Nuno Viana (Gmail) <nuno.carlos.viana@xxxxxxxxx> 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

Current Thread