Dev
Dev

Reputation: 69

XSLT variable issue

I have a xml and I need to transform it using xslt 2.0 to give a different output xml. The output xml needs to have the values of the XSLT variables inside an output xml string. But the XSLT variable values are not being picked up.

Help is highly appreciated. Thanks in advance.

Input xml:`

`<additionalParams> 
    <qryParam name = "rank" value = "300"/>
    <qryParam name = "id" value = "id1"/>
    <qryParam name = "max" value= "max1"/>
</additionalParams> 

Expected output xml:

<additionalParameter name="rank" type="text">
   <value>"300"</value>
</additionalParameter>
<additionalParameter name="id" type="text">
   <value>"id1"</value>
</additionalParameter>
<additionalParameter name="max" type="text">
   <value>"max1"</value>
</additionalParameter>

Current XSLT:

<xsl:for-each select="./additionalParams/qryParam">
    <xsl:variable name = "elmtName" select="@name"/>
    <xsl:variable name = "elmtValue" xsl:value-of select="@value"/>
    <additionalParameter name="$elmtName" type="text">
       <value>"$elmtValue"</value>
    </additionalParameter>
</xsl:for-each>

Current resultant xml after transformation - it is not picking up the variable values.

<otherQueryParameters>
    <additionalParameter name="$elmtName" type="text">
    <value>"$elmtValue"</value>
    </additionalParameter>
    <additionalParameter name="$elmtName" type="text">
        <value>"$elmtValue"</value>
    </additionalParameter>
    <additionalParameter name="$elmtName" type="text">
        <value>"$elmtValue"</value>
    </additionalParameter>
</otherQueryParameters>

Upvotes: 1

Views: 262

Answers (2)

Andreas
Andreas

Reputation: 1250

Be aware that the default way to output values is <xsl:value-of select="your_value"/> where xsl:value-of is an element that has to be put in angle brackets. You missed these in line 3 of your XSLT code, leaving aside that this would be an element inside an element which is not possible. Instead you can use attribute value templates (AVTs) putting the value in curly brackets. This doesn't work in all cases. While typing this, Peter Rader came with a correct answer where the variables should be stripped off as not necessary. You can access the values directly:

<xsl:for-each select="./additionalParams/qryParam">
    <additionalParameter name="{@name}" type="text">
       <value><xsl:value-of select="@value"/></value>
    </additionalParameter>
</xsl:for-each>

Upvotes: 1

Grim
Grim

Reputation: 1974

Try this xslt:

<xsl:for-each select="./additionalParams/qryParam">
    <xsl:variable name = "elmtName" select="@name"/>
    <xsl:variable name = "elmtValue" select="@value"/>
    <additionalParameter name="{$elmtName}" type="text">
       <value><xsl:value-of select="$elmtValue"/></value>
    </additionalParameter>
</xsl:for-each>

Upvotes: 0

Related Questions