Use a XSL Variable in a XML-Tag
I have a XML File I want to transform to XML. And I need to dynamically set the name parameter of XML T开发者_JAVA技巧ags, so it would be something like this:
<VALUE name="$varname"><xsl:value-of select="@value"/></VALUE>
I got something like this:
<xsl:for-each select="PRODTABLE/PRODTR">
<xsl:variable name="varname">
<xsl:copy-of select="PRODTD/PRAT/@name"/>
</xsl:variable>
<VALUE name="$varname">
<xsl:value-of select="PRODTD/PRAT/VALUE"/>
</VALUE>
</xsl:for-each>
But obviously, that doesn't work. Is there a way to achieve this?
This is a FAQ.
The quick answer: An attribute value specified as name="$varname"
is literally the string "$varname".
The way in XSLT to produce an attribute with a dynamically computed value is either to use AVT (Attribute Value Template) or the <xsl:attribute>
instruction.
Solution:
Use:
<VALUE name="{$varname}">
Your code may be re-written in this shorter way:
Instead of:
<xsl:for-each select="PRODTABLE/PRODTR">
<xsl:variable name="varname">
<xsl:copy-of select="PRODTD/PRAT/@name"/>
</xsl:variable>
<VALUE name="$varname">
<xsl:value-of select="PRODTD/PRAT/VALUE"/>
</VALUE>
</xsl:for-each>
use:
<xsl:for-each select="PRODTABLE/PRODTR">
<VALUE name="{PRODTD/PRAT/@name}">
<xsl:value-of select="PRODTD/PRAT/VALUE"/>
</VALUE>
</xsl:for-each>
精彩评论