CDATA sections in XML are used to include text that shouldn't be parsed by the XML parser, such as special characters or reserved words. You can read CDATA content in JavaScript by parsing the XML and accessing the content.
Parse XML and Read CDATA
In this method, we parse an XML string using the DOMParser and access the content inside the CDATA section. CDATA sections are used to include raw text without being parsed by the XML parser.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
const xmlString = `
<note>
<to>John</to>
<from>Jane</from>
<message><![CDATA[Hello, this is a CDATA section!]]></message>
</note>
`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
const cdataContent = xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;
console.log(cdataContent);
// Output: Hello, this is a CDATA section!
</script>
</body>
</html>
Fetch XML File and Read CDATA
In this method, you load an external XML file using the fetch API and then parse the XML to extract the content inside the CDATA section. This is useful when you need to work with XML data hosted remotely.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
fetch("example.xml")
.then(response => response.text())
.then(data => {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(data, "text/xml");
const cdataContent = xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;
console.log(cdataContent);
})
.catch(error => console.error("Error fetching XML:", error));
</script>
</body>
</html>
Use XPath to Locate CDATA
In this method, XPath is used to directly locate and extract the content of the CDATA section. XPath allows you to query XML documents with more precision, making it easier to extract specific elements or text.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
const xmlString = `
<note>
<to>John</to>
<from>Jane</from>
<message><![CDATA[Hello, this is a CDATA section!]]></message>
</note>
`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
const xpathResult = xmlDoc.evaluate("//message/text()", xmlDoc, null, XPathResult.STRING_TYPE, null);
console.log(xpathResult.stringValue);
</script>
</body>
</html>