sergzach
sergzach

Reputation: 6764

Using a Value Of a Variable As a Name For a New Variable

I would like to format a name of a variable dynamically (with help of another variables/parameters) and then use it. In the code below I try to use the value of a variable cur as a name of a variable. But it does not work:

<!-- xml -->
<root>
  <subroot param='1'/>
  <subroot param='2'/>
</root>

<!-- xslt -->
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match='/'>

<xsl:variable name='var1'>Tom</xsl:variable>
<xsl:variable name='var2'>Simone</xsl:variable>

<xsl:for-each select='/root/subroot'>
  <xsl:value-of select='@param'/>

  <xsl:variable name='cur'>var<xsl:value-of select='@param'/></xsl:variable>

  <input value='{${$cur}}'/>

</xsl:for-each>

root found
</xsl:template>

</xsl:stylesheet>

There must be a result:

<input value='Tom'/>
<input value='Simone'/>

Any suggestions how to make it working? Thank you very much for help.

Upvotes: 2

Views: 1114

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243529

  <input value='{${$cur}}'/>

This is illegal syntax in all current and known future versions of XSLT (1.0, 2.0 and 3.0).

And you don't need such capability.

Simply use:

<input value="{$vmyVar[position() = $cur]}"/>

The complete transformation becomes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my" exclude-result-prefixes="my">

 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <my:params>
   <p>Tom</p>
   <p>Simone</p>
 </my:params>

 <xsl:variable name="vmyVar" select=
      "document('')/*/my:params/*"/>

  <xsl:template match='/'>
    <root>
     <xsl:for-each select='/root/subroot'>
      <xsl:variable name='cur' select='@param'/>

      <input value="{$vmyVar[position() = $cur]}"/>
     </xsl:for-each>
    </root>
  </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the following XML document:

<root>
 <subroot param="2"/>
 <subroot param="1"/>
</root>

the wanted, correct result is produced:

<root>
   <input value="Simone"/>
   <input value="Tom"/>
</root>

Upvotes: 1

FailedDev
FailedDev

Reputation: 26930

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xml:space="default">
  <xsl:variable name='var1'>Tom</xsl:variable>
  <xsl:variable name='var2'>Simone</xsl:variable>

  <xsl:template match='/'>
    <root>
    <xsl:for-each select='/root/subroot'>
      <xsl:variable name='cur' select='@param'/>
      <xsl:variable name="curVar" select="document('')/*/xsl:variable[@name= concat('var', $cur)]"/>

      <input value='{$curVar}'/>
    </xsl:for-each>
    </root>
  </xsl:template>

</xsl:stylesheet>

This should do the trick.

Output :

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <input value="Tom"/>
  <input value="Simone"/>
</root>

Upvotes: 1

Related Questions