Search code examples
xpathtype-conversionxslt-2.0

Usage of a variable in an xPath expression


With the definition

<xsl:variable name="testVariable">
    <xsl:value-of select="'/author/'"/> 
</xsl:variable>

I was hoping that

<xsl:value-of select="concat('./book',$testVariable,'@attribute')" />

returns the same like

<xsl:value-of select="./book/author/@attribute" />

But only the latter returns the actual value of the attribute, the first one just returns the path

./book/author/@attribute

How can I make the first one also return the value of the attribute?

Thanks!


Solution

  • The concat() function returns a string, it doesn't magically interpret that string as the source code of an XPath expression and then evaluate that expression.

    Note also that

    <xsl:variable name="testVariable">
        <xsl:value-of select="'/author/'"/> 
    </xsl:variable>
    

    can in 99% of cases be rewritten as

    <xsl:variable name="testVariable" select="'/author/'"/>
    

    which is not only less code, it's also a lot more efficient. (Sadly the other 1% of cases mean that the optimizer can't do this rewrite automatically.)

    Usually you can achieve what you want using

    select="/book/*[name()=$testVariable]/@attribute"
    

    Occasionally you need to go a bit beyond that in which case you need something like xsl:evaluate in XSLT 3.0.