What is the use of CDATA?
Explain me with a good example

Recommended Answers

All 2 Replies

Member Avatar for rajarajan2017

XML CDATA
All text in an XML document will be parsed by the parser.But text inside a CDATA section will be ignored by the parser.

CDATA - (Unparsed) Character Data
The term CDATA is used about text data that should not be parsed by the XML parser.
Characters like "<" and "&" are illegal in XML elements.
"<" will generate an error because the parser interprets it as the start of a new element.
"&" will generate an error because the parser interprets it as the start of an character entity.
Some text, like JavaScript code, contains a lot of "<" or "&" characters.

To avoid errors script code can be defined as CDATA. Everything inside a CDATA section is ignored by the parser.
A CDATA section starts with "<![CDATA[" and ends with "]]>":[/B>]


<script<![CDATA[
function matchwo(a,b)
{
if (a < b && a < 0) then
  {
  return 1;
  }
else
  {
  return 0;
  }
}
]]>
</script>

In the example above, everything inside the CDATA section is ignored by the parser.

Notes on CDATA sections:
A CDATA section cannot contain the string "]]>". Nested CDATA sections are not allowed.
The "]]>" that marks the end of the CDATA section cannot contain spaces or line breaks.

CDATA is special mean in XML. XML has five special meta characters.
1. '(Single quotes)
2. "(Double quotes)
3. &
4. <
5. >

This meta characters may make confusion while parse the xml content in programming.i.e the parser some time treat < and > as element's characters.
For example

<SampleElement> This is special char < in XML </SampleElement>

In the above xml, the parser will read the <(which is in bold) symbol and treat as xml element and expect a name and closing element. This cause produce error,so to eliminate this kind of problem we put these kind of data in CDATA container. CDATA tells parser that following information on it is data not xml element. Simply CDATA will differentiate data and xml element.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.