CDATA Sections
April 5, 2002
Sometimes it is necessary to indicate that a particular block of
text should not be interpreted by the parser. One example is a
large number of occurrences of the five predefined entities in a
block of text that contains no markup, such as a section of code
that needs to test for the numeric less-than or Boolean
&&. In this case, we want text that would
normally be considered markup to be treated simply as literal
character data. CDATA sections are designated portions of
an XML document in which all markup is ignored by the parser and
all text is treated as character data instead. The main uses of
CDATA sections are:
-
to delimit blocks of source code (JavaScript, Java, etc.)
embedded in XML
-
to embed XML, XHTML, or even HTML examples in an XML document
The general syntax for a CDATA section is:
<![CDATA[
multi-line text block to be treated as character data
]]>
No spaces are permitted within the two delimiters
"<![CDATA[" and
"]]>".
Here's a CDATA
section used to escape a block of code:
<![CDATA[
function doIt()
{
var foo = 3;
var bar = 13;
if (foo < 8 && bar > 8)
alert("Help!");
else
alert("I'm Down");
}
]]>
An example of embedded XML in XML follows.
<Example>
<Number>2.4</Number>
<XMLCode>
<![CDATA[
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE Message SYSTEM "message.dtd">
<Message mime-type="text/plain">
<!-- This is a trivial example. -->
<From>The Kenster</From>
<To>Silly Little Cowgirl</To>
<Body>
Hi, there. How is your gardening going?
</Body>
</Message>
]]>
</XMLCode>
</Example>
In contrast to our earlier use of the Message
example, the character data is not simply the three lines of
content of the From, To, and
Body elements. When this example is embedded within
a CDATA section, the entire block is character data,
which in this case means from the XML declaration to and including
the </Message> end tag. In other words, the
XML prolog, the comment, the start and end tags, and so on, are
no longer markup; in this context, they constitute the character
data contained by the CDATA section.
Entity References
XML Family of Specifications: A Practical Guide
Well-Formed vs. Valid Documents
|