XML CDATA, Escaping and Entities: Storing Special Characters Safely
Explain text escaping, CDATA termination, entity expansion and round-trip behavior.
Why a Valid-Looking File Still Breaks the Parser
You paste a block of user-submitted text into an XML element. The file opens without complaint in a text editor and even passes schema validation. Yet when your application loads it, the parser halts with a fatal error at line 42. Or the data survives a round-trip today but corrupts silently tomorrow after a colleague runs a find-and-replace that introduces a reserved character.
XML provides three mechanisms for storing literal &, <, >, ", and ' characters. This article covers when each mechanism applies, how CDATA termination actually works, what entity expansion does to parser memory, and what round-trip testing can and cannot prove.
The Five Characters That Demand an Escape Strategy
XML reserves five characters for markup. If your text contains any of them literally, you must use entity references or a CDATA section. The specification Section 2.4 defines the predefined entities:
| Character | Predefined Entity | Numeric Entity |
|---|---|---|
& |
& |
& |
< |
< |
< |
> |
> |
> |
" |
" |
" |
' |
' |
' |
Observable symptom: The string if (a < b && c > d) placed directly into an element causes the parser to interpret < b as the start of a new tag. Parsing stops or the text after && disappears from the application output.
Entity References: Predictable Substitution
Replace each reserved character with its named or numeric entity. For the string AT&T "value" < 10:
<company>AT&T "value" < 10</company>
A conforming XML parser must expand entity references before handing text to the application. This is required behavior under Section 4.1: the parser replaces the reference with its replacement text during processing.
Diagnosing Double-Escaping
If you pre-escape text in source code and the XML library escapes it again, the output contains AT&amp;T. The application receives the literal string AT&T instead of AT&T. This is the most frequent bug in programmatic XML generation.
Check: Write a test that reads back the exact string you wrote. If the output contains literal & where you expected &, double-escaping is occurring.
Entity Expansion Depth Limits
XML parsers may impose limits on nested entity references. A chain where entity A references entity B, which references entity C, can cause stack overflow or silent truncation. The specification Section 4.1 notes that processors may limit the number of entity references they expand. Avoid nesting entities more than a few levels deep in a single document.
CDATA Sections: Unescaped Text with One Hard Constraint
A CDATA section instructs the parser to treat everything between <![CDATA[ and ]]> as character data, not markup.
<code><![CDATA[if (a < b && c > d) { return "OK"; }]]></code>
The application receives if (a < b && c > d) { return "OK"; } with no escaping required in the source.
The Termination Rule
CDATA sections have exactly one reserved sequence: ]]>. You cannot include this sequence inside a CDATA section under any circumstance — not split across lines, not entity-escaped. The specification Section 2.7 states: "The string ]]> shall not occur in the CDATA section."
Unrecoverable case: If your data contains a literal ]]>, no CDATA-based approach can store it as-is. You must either split the block across two CDATA sections or abandon CDATA entirely for entity references.
Diagnostic step: Search your text for ]]>. If found, split the content:
<text><![CDATA[before]]]]><![CDATA[>after]]></text>
The parser concatenates the two CDATA sections and outputs before]]>after. Alternatively, use entity references for the entire content.
What the Application Sees
The markers <![CDATA[ and ]]> are parser instructions, not data. The application never receives them. When debugging, the raw file may appear cluttered with markup, but the parsed output contains only the text between the markers.
Parser Compatibility
Some parsers written before the XML 1.0 recommendation (1998) or custom parsers that do not implement the full specification treat CDATA sections as unknown markup and strip them. Test with your target parser before relying on CDATA for production data.
Attribute Escaping: Stricter Rules
Inside an attribute value delimited by double quotes, you must escape ", &, and <:
<item name="AT&T "value" < 10"/>
With single-quote delimiters, escape ' and &:
<item name='AT&T 'value' < 10'/>
CDATA sections are invalid inside attribute values. A parser encountering <![CDATA[ in an attribute treats it as literal text, not as an escape mechanism.
Round-Trip Testing: What It Proves
Round-trip testing writes XML, reads it back, and compares the result to the original string. A successful round trip confirms that your escaping mechanism is consistent within that parser.
What It Catches
- Double-escaping (output contains
&instead of&) - Missing escapes (parser fails on unescaped
<) - Encoding mismatches (UTF-8 written, Latin-1 read)
What It Misses
- Parser-specific expansion limits: Parser A may expand 1000 nested entities; Parser B may stop at 50. A test on Parser A reveals nothing about Parser B.
- CDATA termination edge cases: If test data never contains
]]>, you will not discover that production data includes it. - Post-processing corruption: A downstream tool that re-serializes the XML may add or strip CDATA markers, breaking the round trip.
Procedure: Run round-trip tests against at least three parsers (a streaming parser, a DOM parser, and a SAX parser). Use a test corpus that includes all five reserved characters, a text block exceeding 10 KB, and the literal string ]]>.
Entity Expansion and Memory
When a parser expands entity references, it builds the full text in memory. The source file may be small while the expanded content is enormous.
Practical limits: XML 1.0 defines no maximum expansion size, but implementations enforce their own. libxml2 defaults to 10 million characters of expanded text per entity. Expat stops at 100,000 entity references per document. A recursive entity definition such as <!ENTITY x "&x;&x;"> causes exponential expansion. Modern parsers detect recursion and abort. If your application accepts untrusted XML, this is a denial-of-service vector.
Diagnosis: The parser returns an error like "entity expansion too deep" or "out of memory." Reduce entity nesting in your generation code or configure the parser's expansion limit if the setting is exposed.
When Conversion Cannot Recover
A common unrecoverable scenario involves transformation tools that handle escaping inconsistently:
- Input XML contains
]]>inside a CDATA section, which violates the specification. - A lenient parser accepts it and produces output with literal
]]>embedded in text. - A strict parser later rejects that output.
Any conversion that silently drops or corrupts text because a permissive parser accepted invalid input cannot be recovered. Validate XML against a strict parser before any conversion step.
Isolating a Failing Character
Run the file through a strict parser that reports the exact byte position of the first error. Determine whether the problem is an unescaped &, a CDATA section that never closes, or an entity exceeding the expansion limit. Isolate the character, apply the appropriate escape strategy from the table above, and re-test.