CDATA With XSLT

In an XML file you can use CDATA to tell the parser that anything inside the CDATA element is your text data and not XML formatting. In a sense, you can use CDATA to escape data that looks like XML. See Escape From XML. For example, you can escape the ampersand like this:

&

or by using CDATA as in:

<![CDATA[ & ]]>

I often work with XML and XSLT so when I want to treat a block of HTML as data I use the CDATA element in my XML file that will later be transformed with an XSL. For example, in my XML I might have something like this:

<![CDATA[
   <b>this is bold</b>
]]>

In my XSL file, I need to disable the data from being escaped by using the disable-output-escaping of the xsl:value-of tag as in:

<xsl:value-of
   select="."
   disable-output-escaping="yes"/>

If you forget the disable-output-escaping attribute the contents of the CDATA will be escaped, for example < will be transformed to &lt;. With the disable-output-escaping attribute set to yes, the contents from the CDATA will not be escaped and treated as is.

Related posts:

  1. Escape From XML
  2. Using Dom4J: Reading An XML File
  3. WordprocessingML
  4. Flex On Rails
  5. Using Dom4J: Writing An XML

This entry was posted in HTML/XML, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Avinash Yadav
    Posted February 11, 2010 at 5:25 am | Permalink

    Thanks a ton, your tip did help a lot

  2. Posted March 3, 2011 at 3:28 pm | Permalink

    Ah ha, thank you so much! I spent 2 hours trying my damnest to get my line breaks in my XML file to show up properly with my XSLT stylesheet. Many places recommended CDATA, but none of them bothered to mention about the data being escaped!

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*