Subject: RE: [xsl] Adding Variables From: "Andrew Welch" <ajwelch@xxxxxxxxxxxxxxx> Date: Mon, 16 Aug 2004 09:52:08 +0100 |
> What I've never quite understood is how to wrap this into a > conditional. > > Based on http://www.dpawson.co.uk/xsl/sect2/N8090.html#d9711e895 > example, would this be correct for wrapping an assignment in > only if a > variable was passed in, otherwise using the default? > > <xsl:variable name="n"> > <!--Conditionally instantiate a value to be assigned to > the variable > --> > <xsl:choose> > <xsl:when test=="//test1/somevalue1"> > <xsl:variable name="num1" select="//test1/somevalue1"/> > </xsl:when> > <xsl:otherwise> > <xsl:value-of select="20"/><!-- ...or a "20" --> > </xsl:otherwise> > </xsl:choose> > </xsl:variable> Firstly, all equivalence operations in XSLT use a single '=', there is no assignment operator. The example in the faq is trying to demonstrate variable scoping - the areas within the code that a variable is a available to use. <xsl:variable name="n"> <xsl:choose> <xsl:when test="//test1/somevalue1"> <xsl:variable name="num1" select="//test1/somevalue1"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="20"/><!-- ...or a "20" --> </xsl:otherwise> </xsl:choose> </xsl:variable> If the above code was a top-level variable (a child of the xsl:stylesheet element) then the variable 'n' is in scope (available to use) for the entire stylesheet. The variable 'num1' is only in scope within the xsl:when, as soon as the xsl:when is finished 'num1' is out of scope and can no longer be used. The correct way to write the above code is: <xsl:variable name="n"> <xsl:choose> <xsl:when test="//test1/somevalue1"> <xsl:value-of select="//test1/somevalue1"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="20"/> </xsl:otherwise> </xsl:choose> </xsl:variable> This way the variable 'n' is available to the entire stylesheet (providing it's a top-level element) and contains a single child node with the value of the first somevalue1 with a parent test1 in document order if it's present, otherwise the string value 20. With xslt 2.0 you can do the conditional inside the xpath, so to mimic the above code you could use: <xsl:variable name="n" select="if (//test/somevalue1) then //test/somevalue1[1]/text() else 20"/> Cheers andrew
Current Thread |
---|
|
<- Previous | Index | Next -> |
---|---|---|
RE: [xsl] Adding Variables, Michael Kay | Thread | Re: [xsl] Adding Variables, Deirdre Saoirse Moen |
[xsl] simple conditional looping, Keyur K | Date | Re: [xsl] simple conditional loopin, Mukul Gandhi |
Month |