views:

56

answers:

2

When creating XML I'm wondering why the CDATA blocks are uses rather than just escaping the data. Is there something allowed in a CDATA block that can't be escaped and placed in a regular tag?

<node><![CDATA[ ...something... ]]></node>

instead of

<node>...something...</node>

Naturally you would need to escape the data in either case:

function xmlspecialchars($text)
{
    return str_replace('&#039;', '&apos;', htmlspecialchars($text, ENT_QUOTES, 'utf-8'));
}

From the spec it seems that CDATA was just a posible solution when you don't the option to escape the data - yet you still trust it. For example, a RSS feed from your blog (that for some reason or another can't escape entities).

+1  A: 

CDATA is just the standard way of keeping the original text as is, meaning that whatever application processes the XML shouldn't need to take any explicit action to unescape.

You get that typically with JavaScript embedded in XHTML, when you use reserved symbols:

<script type="text/javascript">
//<![CDATA[
    var test = "<This is a string with reserved characters>";

    if (1 > 0) {
        alert(test);
    }
//]]>
</script>

If you had if (1 &gt; 0) instead, it would have to unescape explicitly (which it doesn't). It's also much more readable like this.

Bruno
Ah, I didn't think about using live elements like JS in an XML file. Then again, why aren't we using HTML5? XHTML doesn't even work on most sites when they turn the actual XHTML header on.
Xeoncross
I know this is exaggeration but generally you could say that CDATA is a curiosity that is only needed if you debug XML or misuse XML ;-) (In this tongue-in-cheek context debugging would mean not reading or producing XML programmatically and misusing would mean for example handling XML as not XML. Both of these are happening every day.)
jasso
@Xeoncross, I reckon most browsers support XHTML fairly well nowadays. The trouble is that on the server side, it's not just a matter of putting the XHTML header, the document has to be valid XHTML (and XML) too. One of the uses I've seen of CDATA with JavaScript is for template tools that process XML templates (which may contain some scripts) to produce some (X)HTML.
Bruno
A: 
ZXX