[xsl] Re: passing XSL variables

Subject: [xsl] Re: passing XSL variables
From: Dimitre Novatchev <dnovatchev@xxxxxxxxx>
Date: Tue, 10 Jul 2001 21:44:10 -0700 (PDT)
Jenny Simpson wrote:

[snip]

> I want to use the following bit of code to search the xml document for
> nodes whose year matches a variable $search.
> 
> <xsl:choose>
> 	<xsl:when test="$search">
> 		<xsl:for-each select="bibliography/bibitem">
> 		<xsl:if test="($search=year)">
> ...
> 
> However, instead of using the literal string 'year', I want to use a
> variable containing the string 'year'.  However, if I substitute the
> variable $field (which contains 'year') for 'year', as follows, the
> comparison doesn't work. 
> 
> <xsl:choose>
> 	<xsl:when test="$search">
> 		<xsl:for-each select="bibliography/bibitem">
> 		<xsl:if test="($search=$field)">
> ...
> 
> I've tried using single quotes, parentheses, and even the substring
> function to get the variable to be interpreted as it should be, but to no
> avail.  I'd be interested in any tips on using xsl variables in
> general.  Thanks in advance.

Hi Jenny,

You didn't provide a complete example of your problem, so one has to guess about its
causes.

When specifying the string value of a variable, it may happen that this value
happens to be a syntactically correct XPath expression. In case you do not surround
it in a pair of quotes, then the value of the XPath expression (not the string
itself) will be assigned to the variable.

For example:

<xsl:variable name="var1" select="year"/>

the value of the "var1" variable will be the value of the Xpath expression "year" --
the nodeset containning all "year" children of the current node.

<xsl:variable name="var2" select="'year'"/>

The value of the variable "var2" is the string 'year'

When comparing two variables you have this problem complicated twice (for each of
the variables).

It would help your debugging to output the values of the variables -- surround them
by some visible delimiter, e.g.`, so that leading and trailing spaces are also seen:

<xsl:value-of select="concat('var1=`', $var1, '`')"/>

<xsl:value-of select="concat('var2=`', $var2, '`')"/>


Then you'll immediately know what exactly is happening.

For example, if you discover that $varX is "   year  " , and you wanted to use it as
if it contained "year", you could substitute 

$varX 

in the equality expression with 

normalize-space($varX)


Hope this helped.

Cheers,
Dimitre Novatchev.

__________________________________________________
Do You Yahoo!?
Get personalized email addresses from Yahoo! Mail
http://personal.mail.yahoo.com/

 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread