user899628
user899628

Reputation: 279

how to make an element inside a variable

XSLT 1.0 I will need a variable with the following structure, basically I need to construct a variable which actually is a element. I know it looks silly but I need such thing because of the limitation of other stuff.

 <xsl:variable name="options">
                <xsl:element name="option">
                        <xsl:attribute name="value">
                            <xsl:text>test1</xsl:text>
                        </xsl:attribute>

                       <xsl:text>test1</xsl:text>
                    </xsl:element>
        </xsl:variable>

Now the problem is, when I call it later in the template with

<xsl:value-of select="$options"/>

the output html only have test1 instead of what I want

<option>test1</option>

So it means the tag is missing. What's the right syntax to do this? Thanks in advance!

Upvotes: 2

Views: 1040

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243529

You need to make difference between <xsl:value-of> and <xsl:copy-of>

In XSLT 1.0 the <xsl:value-of> instruction creates a text node that contains the string value of the result of evaluating the XPath expression, specified in the select attribute. By definition, the string value of an element is the concatenation (in document order) of all of its descendent text nodes -- this is how you get the string "test1" output.

By contrast:

<xsl:copy-of>

outputs a copy of every node of the node-set that is selected by the XPath expression specified in the select attribute.

Therefore, in order to copy the complete contents of $options, you need to specify:

<xsl:copy-of select="$options" /> 

Here is a complete example:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="vOptions">
  <option value="test1">test1</option>
 </xsl:variable>

 <xsl:template match="/">
  <xsl:copy-of select="$vOptions"/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on any XML document (not used), the wanted, correct result is produced:

<option value="test1">test1</option>

Upvotes: 2

seanb
seanb

Reputation: 6954

try:

<xsl:copy-of select="$options" />

Upvotes: 1

Related Questions