Example 1 — Create CDATA and Serialize XML
Parse a tiny XML document, append a CDATA section, then serialize it.
const doc = new DOMParser().parseFromString("<xml></xml>", "application/xml");
const cdata = doc.createCDATASection("Some <CDATA> data & then some");
doc.querySelector("xml").appendChild(cdata);
console.log(new XMLSerializer().serializeToString(doc));
// <xml><![CDATA[Some <CDATA> data & then some]]></xml> How It Works
- Parse XML.
application/xmlbuilds a real XML document (not HTML). - Create CDATA.
<and&stay literal inside the section. - Append. The node must be attached before serialization shows it.
- Serialize.
XMLSerializerprints the classic<![CDATA[…]]>wrapper.

