tags:

views:

640

answers:

3

Hello All,

I am using XSLT Transformation and need to put some data in CDATA section and that vale is present in a variable.

Query: How to access variable in CDATA ? Sample Given Below:

<xsl:attribute name ="attributeName">
<![CDATA[ 
  I need to access some variable here like
   *<xsl:value-of select ="$AnyVarible"/>* 
 ]]>
</xsl:attribute>

How can I use varibale in CDATA ? Note: I can not use --> &lt;![CDATA[<xsl:value-of select ="$AnyVarible"/>]]&gt; Thanks in advance.

A: 

CDATA is just text like any other element contents...

But using the xsl:output element you should be able to specify which elements are to be written as CDATA with the cdata-section-elements attribute.

EDIT:

Now that there is a valid sample, I guess you mean this:

<xsl:attribute name ="attributeName">
<![CDATA[ 
   I need to access some variable here like
   *]]><xsl:value-of select ="$AnyVarible"/><![CDATA[* 
]]>
</xsl:attribute>
Lucero
yes... I need to access variable from CDATA<![CDATA[ <xsl:value-of select ="$AnyVarible"/> ]]>
Amit
The `CDATA` cannot contain tags. Therefore you **must** end the `CDATA` section, add the tag, and start another `CDATA` section.
Lucero
@Amit: as per the spec a XML processor must handle CDATA sections the same way they treat simple text. So if some tool only accepts the data inside CDATA, then that tool is broken.
Joachim Sauer
To make any kind of sense, you need to declare `disable-output-escaping="yes"` in a CDATA section. Also there is no CDATA in an attribute value, AFAIK.
Tomalak
A: 

I got the solution for this...FYI for everyone...

<xsl:text
disable-output-escaping="yes">&lt;![CDATA[</xsl:text>
<xsl:value-of select ="$AnyVarible"/>
<xsl:text
disable-output-escaping="yes">]]&gt;</xsl:text>
Amit
The problem with this approach is that you may end up with invalid XML. Also, some XSLT processors (for example the one built into Mozilla Firefox) will not respect the `disable-output-escaping` attribute.
Lucero
@Lucero: *How* can you end up with invalid XML? Unless the variable contains `]]>` of course.
Tomalak
@Tomalak, in this case exactly with the `]]>` case. However, my comment was geared more towards the use of `disable-output-escaping` in general.
Lucero
+1  A: 

If you want to include CDATA sections in your output, you should use the cdata-section-elements atribute of xsl:output. This is a list of element names. Any such elements will have their text content wrapped in CDATA.

<xsl:output cdata-section-elements ="foo" />

<foo>
    <xsl:value-of select="$bar' />
</foo>
Lachlan Roche