XML DOM » Objects » CDATASection

The CDATASection object is used to escape text that contains characters that would otherwise be consideredas markup. The main purpose of this is to hold such things as XML fragments without having to escape all the delimiters, the only one recognized being the '' character sequence that ends the CDATASection. CDATA sections cannot be nested.

The text of a CDATASection is stored in a Text node, and may contain characters that need to be escaped outside of CDATA sections. Unlike Text nodes, however, you cannot merge adjacent CDATA sections using the Element object's normalize method.

A CDATASection has no methods or properties of its own but inherits those of the Text and Node objects. For details of the values returned by the nodeName, nodeType and nodeValue properties for a CDATASection, see the Node object.

Examples

Code:
XML:

<staff>
   <employee ssn="123456" pay="3">
      <f_name><![CDATA[<span style="color:red">John</span>]]><f_name>
      <l_name>Sullivan</l_name>
   </employee>
   <employee ssn="987654" pay="2">
      <f_name>Mary</f_name>
      <l_name>Lopez</l_name>
   </employee>
</staff>

JavaScript:

xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.load("staff.xml");

elem = xml_doc.documentElement.firstChild.firstChild.firstChild;
document.write(elem.nodeName);
document.write("<br>" + elem.nodeType);
document.write("<br>" + elem.data);
Output:
#cdata-section
4
John
Explanation:

In this example we use the 'staff.xml' file. The 'f_name' element of the first 'employee' consists of text which includes HTML SPAN tags with style information. In order to prevent those tags being parsed by the XML parser, we include them in a CDATASection. This allows them to pass through the parser intact and subsequently be applied as normal to the text. Finally the code displays the nodeName, nodeType and data (note the affect of those SPAN tags) properties for the CDATASection.

Language(s): JavaScript XML

Methods

splitText

Syntax: text.splitText(offset)

This method splits a Text node into two at the specified offset. It places all the characters from the offset to the end of the string into a new Text node that immediately follows this one.

See Also: