Check It Yeah, It's On

28Mar/110

Escaping CDATA in XML

What is CDATA?
CDATA is designated as unparsed character data for XML. That is, it should not be parsed by the XML parser.

What is the use of CDATA?
CDATA declarations in XML are used so that they are not parsed by XML. This way, you are able to use characters such as "<" and "&" as data values. CDATA sections are often used to declare code snippets in XML.

Declaring CDATA
In order to declare CDATA in XML, you need to encapsulate the data string in CDATA tags "<![CDATA[" and "]]>" as follows.

Let's say your data string is:

Hello World!

To declare this as CDATA:

<?xml version="1.0" encoding="UTF-8"?>
<mydata><![CDATA[Hello World!]]></mydata>

Now, if your data string contains the CDATA ending tag "]]>" as part of the data, you will need to somehow escape to prevent mis-interpretation. To do this, you should break up the end tag ]]> into two separate CDATA declarations "]]" and ">" as follows.

Let's say your data string is:

Hello]]>World!

The proper way to present this data string as XML CDATA is to separate it into two separate CDATA declarations "Hello]]" and ">World!" as follows:

<?xml version="1.0" encoding="UTF-8"?>
<mydata><![CDATA[Hello]]]]><![CDATA[>World!]]></mydata>
Filed under: Code Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.