开发者

Why should you use XML CDATA blocks?

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 开发者_StackOverflow社区another can't escape entities).


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.


It's first and most of all readability feature. XML, and SGML before it were originally meant to be human readable - believe it or not :-))

Second, for a good parser it's a perf feature. The ]]> ending is guaranteed to be the actual block ending but apart from that it's a blob.

By the book parser should also keep the info/attrib on a node representation to track that it has explicit CDATA and never ever touch a single char in it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜