Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a variable in XSLT select

Tags:

xml

xslt

xslt-2.0

I am trying to make a named template or function where I an pass in a node name and it will select that as the last level of a xpath expression. But all it returns is the string I pass in as a param. In the below example the value returned is "name"

XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output indent="yes"></xsl:output>

    <xsl:template name="get-prefered">
        <xsl:param name="field-name"/> 

        <xsl:variable name="vCondition" select="name"/>
        <xsl:variable name="x" select="sources/source[@type='C']/$field-name"/>
        <xsl:value-of select="$x"></xsl:value-of>
    </xsl:template>

    <xsl:template match="/">
        <xsl:call-template name="get-prefered">
            <xsl:with-param name="field-name">name</xsl:with-param>
        </xsl:call-template>
        </xsl:template>
</xsl:stylesheet>

INPUT XML:

<?xml version="1.0" encoding="UTF-8"?>
<sources>
    <source type='C'>
        <name>Joe</name>
        <age>10</age>
    </source>
    <source type='B'>
        <name>Mark</name>
        <age>20</age>
    </source>
</sources>
like image 206
Alex Avatar asked May 01 '26 22:05

Alex


2 Answers

change

<xsl:variable name="x" select="sources/source[@type='C']/$field-name"/>

to

<xsl:variable name="x" select="sources/source[@type='C']/*[name()=$field-name]"/>

it returns:

Joe
like image 55
Joel M. Lamsen Avatar answered May 04 '26 01:05

Joel M. Lamsen


The problem here:

select="sources/source[@type='C']/$field-name"

is that the variable $field-name contains a string, not a location path - so that the expression expands to:

select="sources/source[@type='C']/'name'"

If you're using an XSLT 2.0 processor, then you are likely to have access to an evaluate() function that can convert a string into a path, e.g. http://www.saxonica.com/documentation9.4-demo/html/extensions/functions/evaluate.html Otherwise you'll need to use some other method - for example, the one shown by Joel M. Lamsen in his answer.

like image 34
michael.hor257k Avatar answered May 04 '26 01:05

michael.hor257k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!