[XSL-LIST Mailing List Archive Home] [By Thread] [By Date] [Recent Entries] [Reply To This Message]

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

Subject: Re: [XSLT]: Recursive Function to Add/Multiply
From: "Andrew Welch" <andrew.j.welch@xxxxxxxxx>
Date: Mon, 9 Oct 2006 09:53:01 +0100
xslt add function
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

PURCHASE STYLUS STUDIO ONLINE TODAY!

Purchasing Stylus Studio from our online shop is Easy, Secure and Value Priced!

Buy Stylus Studio Now

Download The World's Best XML IDE!

Accelerate XML development with our award-winning XML IDE - Download a free trial today!

Don't miss another message! Subscribe to this list today.
Email
First Name
Last Name
Company
Subscribe in XML format
RSS 2.0
Atom 0.3
Site Map | Privacy Policy | Terms of Use | Trademarks
Free Stylus Studio XML Training:
W3C Member
Stylus Studio® and DataDirect XQuery ™are products from DataDirect Technologies, is a registered trademark of Progress Software Corporation, in the U.S. and other countries. © 2004-2013 All Rights Reserved.