Parse your character data using CDATA section

XML parser normally parse all the text in an XML document.

 

Characters such as less than (<), greater than(>), ampersands(&) etc cause problems for the XML processor/parser.

 

“<” parser interprets it as the start of a new element.
“&” parser interprets it as the start of an character entity.
JavaScriptcode,contains a lot of “<” or “&” characters.To avoid errors script code can be defined as CDATA.

 

CDATA section tell the parser that there is no markup in the characters contained by the CDATA section
Parsed character data (PCDATA) is a term used about text data that will be parsed by the XML parser.
CDATA is used for (Unparsed) character data.

 

A CDATA section starts with “<![CDATA[” and ends with “]]>”

example :
<script>
<![CDATA[
function function_name()
{
if (condition1 && condition2) {
return 1;
}else {
return 0;
}
}
]]>
</script>

 

A CDATA section is also required if you are using XHTML and validating it, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files(.js file),but for any inline JavaScript in XHTML ,it will better to use in a CDATA section.

 

example:
<script>
//<![CDATA[
..your code will go here..
//]]>
</script>

 

Notes :

  • Nested CDATA sections are not allowed.
  • A CDATA section cannot contain the string “]]>”.
  • The “]]>” (end of the CDATA section) cannot contain spaces/line breaks.