rumpel
rumpel

Reputation: 8308

How to use variables in xslt xpath expressions

I have something like the following code::

<xsl:variable name="sample">
     <xsl:copy-of select="//foo">
     <xsl:copy-of select="//bar">
</xsl>

And in a template I’d like to use:

<xsl:for-each select="$sample/*">
    <!-- do something -->
</xsl:for-each>

However, $sample/* does not seem to be a valid xpath expression or return a node-set and I can't quite figure out, how to fix it. I also tried just plain $sample, but that isn't a node-set either :/ Any ideas, what I’m doing wrong?

Upvotes: 0

Views: 2124

Answers (2)

Maestro13
Maestro13

Reputation: 3696

There's actually two other solutions available next to switching to an XSLT 2.0 processor.
One is applying a processor dependent function as Kevan says, for instance msxsl:node-set() or xalan:nodeset() or exsl:node-set().
The other is to make use of the fact that xsl:variable select attribute includes a conversion of a result tree fragment such as your sample variable to a node-set; hence defining a new variable with select attribute equal to the one to be addressed, will do the trick:

<xsl:variable name="temp" select= "$sample"/>
<xsl:for-each select="$temp/*">
    <!-- do something -->
</xsl:for-each>

Upvotes: 0

Kevan
Kevan

Reputation: 891

Are you using XSLT 1? You can't apply xpath expressions to variables in XSLT 1. You can in XSLT 2 however.

Depending on your XSLT processor you may have access to a custom extension such as EXSLT's node-set function.

Upvotes: 4

Related Questions