2026-09-01 · 8 min read
- xml
- integration
- serialization
XML character data normally escapes ampersand and less-than signs as entities. A CDATA section provides a lexical convenience for text containing many markup-like characters, but it does not create a different application data type after parsing.
The sequence ]]> cannot appear inside one CDATA section because it closes the section. Serializers may also replace CDATA with escaped text or combine adjacent text nodes while preserving the parsed character value.
Choose based on the parsed data model
Use ordinary character data by default and let an XML serializer escape it. Use CDATA only when an integration or human-authored format benefits from that representation, not as a security boundary or a way to embed active XML markup.
- Create text nodes rather than concatenating XML strings.
- Represent child markup as nodes, not text hidden in CDATA.
- Split any CDATA closing sequence with adjacent text sections.
- Keep binary bytes out of XML character data unless encoded by schema.
Preserve encoding and Unicode correctly
The XML declaration, transport metadata, and actual bytes must agree on character encoding. Decode bytes once at the boundary and pass Unicode strings to the serializer; do not pre-escape text before assigning it to a text node.
Base64 is appropriate when a schema explicitly carries binary data. State the Base64 profile and size limits, and validate decoded content separately from XML well-formedness.
Separate value equivalence from byte equivalence
CDATA and escaped text can parse to the same character sequence while producing different bytes. Compare parsed values for application behavior, but use the signature specification's canonicalization algorithm when cryptographic integrity covers XML.
- Do not hand-normalize signed XML before verification.
- Keep namespace and character-data concerns separate.
- Bound entity expansion and disable unsafe external resolution.
- Log locations and error classes without dumping confidential documents.
Build serializer round-trip tests
Use Flashman's XML formatter with public fixtures, HTML entities tool to inspect escaped characters, diff to compare serializations, Base64 for schema-defined binary samples, and hash tool for byte-level fixture labels.
Test empty text, ampersands, markup-like text, the CDATA terminator at every boundary, Unicode and encodings, adjacent text nodes, schema validation, canonical signatures, and round trips through each producer and consumer.