XML technologies / XML / XML in a Nutshell / XML basics / CDATA sections

(Excerpt from "XML in a Nutshell" by Elliotte Rusty Harold & W. Scott Means)

When an XML document contains XML or HTML source code examples, the characters < and & in those examples must be encoded as &lt; and &amp;. The more such code a document contains and the longer the examples, the more tedious this becomes. Instead, you can enclose each example in a CDATA section. A CDATA section is enclosed by <![CDATA[ and]]>. Everything between <![CDATA[ and ]]> is interpreted as plain character data. Less-than signs do not start tags, and ampersands do not introduce entity references. There is only character data, with no markup.

In a Scalable Vector Graphics (SVG) tutorial written in XHTML, you might see the following:

<p>Sie können ein vorgegebenes <code>xmlns</code>-Attribut benutzen, damit Sie nicht allen Ihren Elementen das Präfix svg hinzufügen müssen:</p>
  <pre><![CDATA[
    <svg xmlns="http://www.w3.org/2000/svg" width="12cm" height="10cm">
      <ellipse rx="110" ry="130" />
      <rect x="4cm" y="1cm" width="3cm" height="6cm" />
    </svg>
 ]]></pre>

The SVG source code has been inserted directly into the XHTML file without carefully replacing each < with &lt;. The result is an example SVG document, not an embedded SVG image, as it would be if the example were outside a CDATA section.

The only thing that cannot occur in a CDATA section is its closing delimiter ]]>.

CDATA sections are intended for authors’ convenience, not for programs. Parsers need not report whether a text block came from a CDATA section, ordinary character data, or character data containing entity references such as &lt; and &amp;. Once you receive the data, these differences may no longer be visible. Your code should never depend on them.

  

 

 

 

back to top