Mohamed Saligh
Mohamed Saligh

Reputation: 12339

Why XML tag data inside this <![CDATA[]]>

I have seen in many XML file has the data inside this <![CDATA[ ]]>. What is the use of this?

Upvotes: 3

Views: 12021

Answers (4)

Tiago
Tiago

Reputation: 934

Anything inside a CDATA section is ignored by the parser.

For instance image that you want to send javascript inside an xml document, since it will most probably contain special chars (<,>,&, etc) the xml parser will produce errors.

With this tag the parser will not parse it and no errors will be produced.

Upvotes: 0

Tyler Eaves
Tyler Eaves

Reputation: 13121

It allows literal text, including most xml "special characters". it's not part of the "outer" xml data but just text.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816232

See CDATA at Wikipedia:

In an XML document or external parsed entity, a CDATA section is a section of element content that is marked for the parser to interpret as only character data, not markup.

That means the parser will not interpret any data contained in <![CDATA[ ]]>.

Lets say you want to store HTML as text in an XML document. This is wrong:

<root>
    <myhtml>
        <div><b>Foo bar</b></div>
    </myhtml>
</root>

The parser would try to parse <div><b>Foo bar</b></div> and create DOM elements. It would work in this example, but not for documents that conform to an DTD.

Instead, we want this:

<root>
    <myhtml>
        <![CDATA[ <div><b>Foo bar</b></div> ]]>
    </myhtml>
</root>

and <div><b>Foo bar</b></div> will become the content of a text node.

Upvotes: 3

Neil Knight
Neil Knight

Reputation: 48537

From Wikipedia

A CDATA section starts with the following sequence:

<![CDATA[

and ends with the first occurrence of the sequence:

]]>

All characters enclosed between these two sequences are interpreted as characters, not markup or entity references. For example, in a line like this:

<sender>John Smith</sender>

the opening and closing "sender" tags are interpreted as markup. However, if written like this:

<![CDATA[<sender>John Smith</sender>]]>

then the code is interpreted the same as if it had been written like this:

&lt;sender&gt;John Smith&lt;/sender&gt;

Check out the Wiki page for more details.

Upvotes: 6

Related Questions