RE: [xsl] concat string to an variable name

Subject: RE: [xsl] concat string to an variable name
From: "Andrew Welch" <AWelch@xxxxxxxxxxxxxxx>
Date: Fri, 2 Apr 2004 11:38:51 +0100
> I have variables like this: (and many more)
> <xsl:variable name="HE01_1">-30 min.</xsl:variable> 
> <xsl:variable name="HE02_1">08:00</xsl:variable>
> ...
> <xsl:variable name="HE01_2">Day 1, 08:00</xsl:variable>
> ...
> <xsl:variable name="HE11_8">Day 11, 08:00</xsl:variable>
> 
> At runtime I want to return one of this variables. Which 
> variable is the right is determined on the basis two values. 
> 1. The Element <PRINTTYP/> which has values like 'HE01', 
> 'HE02' ans so on. 2. A other Element <ROW/> which has values 
> like '1', '2' ans so on.
> 
> 
> I concat both values like:
> <xsl:value-of selct="concat($Printtyp, '_', $Row)"/>
> 
> to create a string matching an variable name like 'HE01_1'.
> 
> My question now is, how can I select the variable whish name 
> matches the createt string? 
> Is this possible?

You can use the fact that calling document() with an emtpy string
returns the stylesheet itself, you can the query the stylesheet as
thought it was the source document.

Create a variable containing the name of the variable you are trying to
query:

 <xsl:variable name="varName" select="concat('HE01','_2')"/>

Create a source document out of the stylesheet and then locate the node
you are after:

 <xsl:value-of select="document('')/*/xsl:variable[@name=$varName]"/>

Of course instead of storing all of those values as variables in the
first place, you could just store them in a single temporary tree and
query that directly.  For example:

 <xsl:variable name="tempTree">
   <node first="HE01" second="1">-30 min.</node> 
   <node first="HE02" second="2">08:00</node>
 </xsl:variable>

(I don't know what your data means, so Ive used 'first', 'second' and
'node' etc you would choose much better names :)

Then you can use simply:

 <xsl:value-of
select="$tempTree/node[@first='whatever'][@second='whatever']]"/>

This doesn't incur the cost of building a tree out of the stylesheet,
but does require you have control over your variable definitions (as the
stylesheet writer you should do!)

cheers
andrew

Current Thread