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 |
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?
<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>
If you are using XSLT 2.0 then you can drop the choose/when for the more terse if then else:
cheers andrew
Current Thread |
---|
|
<- Previous | Index | Next -> |
---|---|---|
[xsl] [XSLT]: Recursive Function to, Nuno Viana (Gmail) | Thread | RE: [xsl] [XSLT]: Recursive Functio, Michael Kay |
[xsl] [XSLT]: Recursive Function to, Nuno Viana (Gmail) | Date | RE: [xsl] [XSLT]: Recursive Functio, Michael Kay |
Month |