RE: [xsl] Set variable via contents of <variable> element

Subject: RE: [xsl] Set variable via contents of <variable> element
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Thu, 17 Dec 2009 13:45:38 -0000
> As I understand it, I can set the value of a variable in two ways:
> 1. By the "select" attribute of the <variable> element:
> <xsl:variable name="myvariable" select="'myvalue'"/>
> 2. By the contents of the <variable> element:
> <xsl:variable name="myvariable">
>   My value
> </xsl:variable>

Which have completely different effects. In the first case, the value of the
variable is a string. In the second it is a tree of nodes: a document node,
with a text node child containing the string "My value" (plus surrounding
whitespace). Incidentally the second form can be dramatically slower than
the first.
> But how do I set the variable using the second method? 

In XSLT 1.0 you can't.

In XSLT 2.0 you could use

<xsl:variable name="x" as="node()">
  <xsl:sequence select="..."/>
> The reason I need to do this is because I want to set the 
> variable 'usethis'
> to the result of a <choose> element which (as far as I know) 
> I cannot include in a "select" attribute. 

Yes, in XSLT 1.0 this is a problem. Sometimes a workaround is to use

<xsl:variable select="expr1[condition] | expr2[not(condition)]"/>

which is equivalent to the XSLT 2.0

<xsl:variable select="if (condition) then expr1 else expr2"/>


Michael Kay 

Current Thread