About
A cdata section 1) delimits a text as being cdata (character data). It's used mostly to be able to use (ie escape) reserved xml characters that would otherwise be recognized as xml markup.
Example
An example of a CDATA section, in which
andare recognized as character data, not xml markup:
<![CDATA[<greeting>Hello, world!</greeting>]]>
HTML and XHTML compliancy
CDATA works only in strict XML language, therefore, if you want your document to be correctly parsed :
- by a XHTML parser (that does recognise the CDATA sections)
- and HTML parser (that does not recognise the CDATA sections) 2)
you have the following solutions:
Entity encoding
You can encode the reserved character with an HTML entity.
For instance, the above example would become:
<greeting>Hello, world!</greeting>
where every reserved character was transformed as an entity. For instance, the less than character was encoded as <.
The above entity syntax is then rendered correctly in HTML as seen below:
Commenting out cdata delimiters
A common solution is to comment out, the CDATA delimiters symbols.
- In XHTML, you will get a cdata section and a text node for the comments characters
- in HTML, you will have to delete the delimiters (if you want to grab the content)
For instance:
- In Javascript:
<script>
//<![CDATA[
document.write("< is greater than >");
//]]>
</script>
- Or in css:
<style type="text/css">
/*<![CDATA[*/
body { background-image: url("illustration.png?width=1200&height=600") }
/*]]>*/
</style>
Syntax
CDATA sections:
- begin with the string <![CDATA[
- and end with the string ]]>
CDATA sections may occur anywhere character data may occur.