views:

744

answers:

3
A: 
bobince
+4  A: 

According to HOWTO Avoid Being Called a Bozo When Producing XML:

Don’t bother with CDATA sections

XML provides two ways of escaping markup-significant characters: predefined entities and CDATA sections. CDATA sections are only syntactic sugar. The two alternative syntactic constructs have no semantic difference.

CDATA sections are convenient when you are editing XML manually and need to paste a large chunk of text that includes markup-significant characters (eg. code samples). However, when producing XML using a serializer, the serializer takes care of escaping automatically and trying to micromanage the choice of escaping method only opens up possibilities for bugs.
...
Only <, >, & and (in attribute values) " need escaping.

So long as the small set of special characters are encoded/escaped it should just work.

Whether you have to handle the escaping yourself is a different matter, but certainly a much more straightforward-to-solve problem.

Then just append the whole lot as a child text node to the relevant XML element.

Jon Cram
This makes it easy. Thanks.
nc
+1  A: 

I know of exactly two real use cases for CDATA:

One is in an XHTML document containing script:

<script type="text/javascript">
<![CDATA[
   function foo()
   {
      alert("You don't want <this> text escaped.");
   }
]]>
</script>

The other is in hand-authored XML documents where the text contains embedded markup, e.g.:

<p>
   A typical XML element looks like this:
</p>
<p>
   <pre>
   <![CDATA[
      <sample>
         <text>
            I'm using CDATA here so that I don't have to manually escape
            all of the special characters in this example.
         </text>
      </sample>
   ]]>
   </pre>
</p>

In all other cases, just letting the DOM (or the XmlWriter, or whatever tool you're using to create the XML) escape the text nodes works just fine.

Robert Rossney
A good approach to avoid needing a CDATA section around a script is to use JavaScript string literal escaping: alert("You don't want \x3Cthis\x3E text escaped.");
bobince