Search code examples
xmlcdata

What is the Point of using XML CDATA?


I was reading up on XML files and came across this <![CDATA[]]>.

In what sort of situation would this be useful?

I understand it being used as;

All text in an XML document will be parsed by the parser.

But text inside a CDATA section will be ignored by the parser.

from here. However, It doesn't exactly go into any detail of when it may be useful and/or its relevance to xml files/etc.

This SO question asks what does it mean, but again, not too much detail from what i can see of what does it do nor when should i use it - which is why I am asking this question now.

(i'm not exactly a pro, nor an adept - ok, more of a complete idiot actually - even reading the docs didn't actually help, so any comprehensive answers would be great :P)


Solution

  • You can use it to avoid XML escaping special characters.

    Imagine you have an element like

    <data>...</data>

    And want to place the following text in the data element :

     a < b
    

    Like so:

    <data>a < b</data> 
    

    That doesn't work, since XML recognizes the < as a potential start of a new tag.

    You can escape the < character:

    <data>a &lt; b</data>
    

    Or you can tell the XML parser to not parse your data by placing it in a CDATA section:

    <data><![CDATA[a < b]]></data>
    

    (Then again, with CDATA, your text cannot contain ]]>)

    See also this question