tags:

views:

281

answers:

4
+1  Q: 

XSLT variables

I am trying to learn XSLT. I am simply getting crazy. Variables should be declared within xsl:variables entity and instantiated with their names having the $ symbol just before them (like perl variables), right? Why on earth this code:

<xsl:stylesheet version="1.0"  
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;

    <xsl:template match="/">
     <xsl:variable name="color" select="'red'" />
     <p>$color</p>
    </xsl:template>
</xsl:stylesheet>

results in the literal string: "$color" being written parsing a simple non empty xml document using the msxsl parser? Many thanks

+14  A: 

Use <xsl:value-of select="$color"/> instead of writing $color directly to the document.

See also this question.

Joey
+8  A: 

Also, within attributes you can get to the values directly like this:

<span style="color:{$color}" />
Peter Lillevold
+1 - all these years I've been using <xsl:attribute> to do this - why did nobody tell me before!
Phil Nash
ditto... and the worst part is, I've seen it before and forgot. :(
harpo
Glad to spread some joy - @Phil, your words are quite similar to mine when I discovered this too!
Peter Lillevold
+2  A: 

Why on earth this code: ...

<xsl:variable name="color" select="'red'" /> <p>$color</p>

results in the literal string: "$color" being written

Because this code means: output the string $color as the text node child of the <p> element.

To output the value of the $color xsl:variable use one of these:

  • <xsl:value-of select="$color"/>
  • <xsl:copy-of select="$color"/>
Dimitre Novatchev
+2  A: 

A good rule of thumb for xslt: if it's not in an <xsl:foo> tag, it's not code. It's output.

jrb