Rod
Rod

Reputation: 15475

XSLT: Can a node be a variable and used elsewhere?

xsl

<xsl:variable name="varName>
  <xsl:value-of select="/can/be/a/long/path/down/xml/item[@id=1] />
</xsl:variable>

xml

<xml>
  <item id="1" text="Yes">
  <item id="2" text="No">
</xml>

use

I was thinking I could use like this:

<xsl:when test="$varName/@text = 'Yes'">
blah
</xsl:when>

but blank space is generated in place of variable. Is this even possible, have a node as a variable and use elsewhere?

Upvotes: 0

Views: 50

Answers (1)

Michael Kay
Michael Kay

Reputation: 163458

<xsl:variable name="varName">
  <xsl:value-of select="/can/be/a/long/path/down/xml/item[@id=1]" />
</xsl:variable>

This is one of the most common XSLT errors I see. Usually what people intended is:

<xsl:variable name="varName" select="/can/be/a/long/path/down/xml/item[@id=1]"/>

And most of the time, the code works just fine, except that it's a lot slower than it needs to be. But sometimes the fact that the two constructs are quite different beneath the covers comes back to bite you.

To understand the difference, xsl:variable with a select attribute binds the variable to whatever the select expression evaluates to, which in this case is a set of zero or more item elements. By contrast, xsl:variable with nested instructions creates a document node (XSLT 2.0) or result tree fragment (XSLT 1.0) whose content is a COPY of whatever those instructions produce. In this case, because the content is an xsl:value-of instruction, the variable contains a copy of the string-value of the selected node.

And of course, the string value of the selected node doesn't have any attributes, so test="$varname/@text = 'x'" will always return false.

Upvotes: 4

Related Questions