XSLT creates node name from variable
When I have these two variables
<xsl:variable name="a" select="'Total'" />
<xsl:variable name="b" select="'500'" />
I would like to create a node with the variable name 'a' and its content from the variable 'b'. I have to use xsltproc with XSLT 1.0 and several EXSLT extensions (node-set among them), so I got part of it:
<xsl:template match="/">
<xsl:variable name="x" >
<<xsl:value-of select="$a" />>
<xsl:value-of select="$b" />
</<xsl:value-of select="$a" />>
</xsl:variable>
<xsl:value-of disable-output-escaping="yes" select="$x" />
</xsl:template>
really does highlight this (I'm not interested in whitespace at the moment):
<?xml version="1.0"?>
<Total>
500
</Total>
But : I want to use the variable 'x' as a node so that it can be manipulated (of course my real life example is more complicated). I did a conversion to node-set (using exslt.org/common), which seems to work, but content access does not.
<xsl:variable name="nodes" select="common:node-set($x)" />
<xsl:value-of select="$nodes/Total" />
leads nothing. I would expect " 500 " as $ nodes / Total must be a valid XPATH 1.0 expression. Obviously I am missing something. I guess the point is that dynamically creating a node name with <...>
doesn't actually create a node, but just some textual output, so how can I create a true node here?
source to share
This transformation :
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="http://exslt.org/common" exclude-result-prefixes="ext">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:variable name="a" select="'Total'" />
<xsl:variable name="b" select="'500'" />
<xsl:template match="/*">
<xsl:variable name="rtfX">
<xsl:element name="{$a}">
<xsl:value-of select="$b"/>
</xsl:element>
</xsl:variable>
<xsl:value-of select="ext:node-set($rtfX)/Total"/>
</xsl:template>
</xsl:stylesheet>
if applied to any XML document (not used) produces the desired, correct result:
500
source to share