XML CDATA
XML CDATA Sections
Section titled “XML CDATA Sections”By default, all text content within an XML document is parsed by the XML parser.
However, text enclosed within a CDATA section is treated as raw character data and ignored by the parser.
PCDATA - Parsed Character Data
Section titled “PCDATA - Parsed Character Data”XML parsers process the text content found between the start and end tags of elements. This content is known as Parsed Character Data (PCDATA).
For example, in the following snippet, the text “This text is also parsed” is PCDATA:
<message>This text is also parsed</message>Parsers need to process this data because it might contain nested XML elements, requiring further breakdown. Consider this example:
<name> <first>Bill</first> <last>Gates</last></name>The parser recognizes <first> and <last> as child elements within <name>, interpreting the document’s structure.
PCDATA is the standard way text content within XML is handled, allowing for nested structures and entity processing.
CDATA - Character Data (Unparsed)
Section titled “CDATA - Character Data (Unparsed)”CDATA refers to blocks of text that you want the XML parser to ignore completely. It treats the content as literal characters, without interpreting any potential markup.
This is crucial because certain characters have special meaning in XML, primarily ’<’ (starts a tag) and ’&’ (starts an entity). Including these directly within element content can lead to parsing errors.
For instance, ’<’ would make the parser think a new element is beginning.
’&’ would make the parser expect a valid entity reference (like & or <).
Text containing code snippets (like JavaScript or XML examples) often includes these characters. To prevent errors, such content can be wrapped in a CDATA section.
A CDATA section starts with <![CDATA[ and ends with ]]>. Everything in between is passed through without parsing.
<script type="application/javascript"><![CDATA[ function compareValues(a, b) { if (a < b && a < 0) { // The '<' and '&' characters are safe here return 1; } else { return 0; } }]]></script>In the example above, the JavaScript code within the CDATA section is ignored by the XML parser, preventing errors caused by the < and && operators.
Important Notes on CDATA Sections:
- A CDATA section cannot contain the literal string
]]>. If you need to include this sequence, you’ll have to split the CDATA section. - Nested CDATA sections are not permitted.
- There should be no spaces or line breaks within the closing
]]>marker.
While CDATA is useful, excessive use can sometimes indicate that XML might not be the best format for the data (e.g., embedding large, complex non-XML blocks). Consider alternatives if this becomes common.