A CDATA section is "a section of element content that is marked for the parser to interpret as only character data, not markup."
Syntactically, it behaves similarly to a comment:
<exampleOfAComment>
<!--
Since this is a comment
I can use all sorts of reserved characters
like > < " and &
or write things like
<foo></bar>
but my document is still well-formed!
-->
</exampleOfAComment>
... but it is still part of the document:
<exampleOfACDATA>
<![CDATA[
Since this is a CDATA section
I can use all sorts of reserved characters
like > < " and &
or write things like
<foo></bar>
but my document is still well formed!
]]>
</exampleOfACDATA>
Try saving the following as a .xhtml
file (not .html
) and open it using FireFox (not Internet Explorer) to see the difference between the comment and the CDATA section; the comment won't appear when you look at the document in a browser, while the CDATA section will:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
<head>
<title>CDATA Example</title>
</head>
<body>
<h2>Using a Comment</h2>
<div id="commentExample">
<!--
You won't see this in the document
and can use reserved characters like
< > & "
-->
</div>
<h2>Using a CDATA Section</h2>
<div id="cdataExample">
<![CDATA[
You will see this in the document
and can use reserved characters like
< > & "
]]>
</div>
</body>
</html>
Something to take note of with CDATA sections is that they have no encoding, so there's no way to include the string ]]>
in them. Any character data which contains ]]>
will have to - as far as I know - be a text node instead. Likewise, from a DOM manipulation perspective you can't create a CDATA section which includes ]]>
:
var myEl = xmlDoc.getElementById("cdata-wrapper");
myEl.appendChild(xmlDoc.createCDATASection("This section cannot contain ]]>"));
This DOM manipulation code will either throw an exception (in Firefox) or result in a poorly structured XML document: http://jsfiddle.net/9NNHA/