XSL: How best to store a node in a variable and then use it in future xpath expressions?

Try this example:

<xsl:variable name="hotels" select="/results/hotels[active='true']" />
<xsl:variable name="three_star_or_less"
              select="$hotels[number(rating) &lt;= 3]" />
<xsl:for-each select="$three_star_or_less">
    <xsl:sort select="rating" />
    <xsl:value-of select="rating" />
</xsl:for-each>

There is no problem storing a node-set in a variable in XSLT 1.0, and no extensions are needed. If you just use an XPath expression in select attribute of xsl:variable, you'll end up doing just that.

The problem is only when you want to store the nodes that you yourself had generated in a variable, and even then only if you want to query over them later. The problem here is that nodes you output don't have type "node-set" - instead, they're what is called a "result tree fragment". You can store that to a variable, and you can use that variable to insert the fragment into output (or another variable) later on, but you cannot use XPath to query over it. That's when you need either EXSLT node-set() function (which converts a result tree fragment to a node-set), or XSLT 2.0 (in which there are no result tree fragments, only sequences of nodes, regardless of where they come from).

For your example as given, this doesn't seem to be a problem. Rubens' answer gives the exact syntax.


Another note, if you want to be able to use the variable as part of an XPath statement, you need to select into the variable with <xsl:copy-of select="."/> instead of <xsl:value-of select="."/>

value-of will only take the text of the node and you wont be able to use the node-set function to return anything meaningful.

<xsl:variable name="myStringVar">
   <xsl:value-of select="."/>
</xsl:variable>

<!-- This won't work: -->
<Output>
   <xsl:value-of select="node-set($myStringVar)/SubNode" />
</Output>


<xsl:variable name="myNodeSetVar">
   <xsl:copy-of select="."/>
</xsl:variable>

<!-- This will work: -->
<Output>
   <xsl:value-of select="node-set($myNodeSetVar)/SubNode" />
</Output>

Tags:

Xpath

Xslt