为什么要使用 XML CDATA 块? [英] Why should you use XML CDATA blocks?

查看:26
本文介绍了为什么要使用 XML CDATA 块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建 XML 时,我想知道为什么使用 CDATA 块而不是仅仅转义数据.CDATA 块中是否允许某些无法转义并放置在常规标签中的内容?

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>

代替

<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'));
}

规范 看来,CDATA 是当您无法选择转义数据时,这只是一个可行的解决方案 - 但您仍然信任它.例如,来自您博客的 RSS 提要(出于某种原因无法转义实体).

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).

推荐答案

CDATA 只是保持原始文本原样的标准方式,这意味着无论应用程序如何处理 XML,都不需要采取任何显式操作来取消转义.

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.

当您使用保留符号时,您通常会通过嵌入在 XHTML 中的 JavaScript 获得这一点:

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 (1 &gt; 0) 代替,它必须显式地转义(它没有).像这样也更具可读性.

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.

这篇关于为什么要使用 XML CDATA 块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆