我经常在XML文件中发现这个奇怪的CDATA标签:

<![CDATA[some stuff]]>

我观察到这个CDATA标记总是出现在开头,然后跟着一些东西。

但有时用,有时不用。我假设这是为了标记一些东西是“数据”,将被插入之后。但是什么是数据呢?我用XML标记写的东西不是某种数据吗?


当前回答

当我的xml元素需要存储HTML代码时,我曾经不得不使用CDATA。类似的

<codearea>
  <![CDATA[ 
  <div> <p> my para </p> </div> 
  ]]>
</codearea>

CDATA意味着它会忽略任何可以被解释为XML标签的字符,比如<和>等。

其他回答

通常用于在XML文档中嵌入自定义数据,如图片或声音数据。

一个大的用例:你的xml包含一个程序,作为数据(例如Java的网页教程)。在这种情况下,您的数据包含大量字符,其中包括'&'和'<',但这些字符并不是xml字符。

比较:

<example-code>
while (x &lt; len &amp;&amp; !done) {
    print( &quot;Still working, &apos;zzz&apos;.&quot; );
    ++x;
    }
</example-code>

with

<example-code><![CDATA[
while (x < len && !done) {
    print( "Still working, 'zzzz'." );
    ++x;
    }
]]></example-code>

Especially if you are copy/pasting this code from a file (or including it, in a pre-processor), it's nice to just have the characters you want in your xml file, w/o confusing them with XML tags/attributes. As @paary mentioned, other common uses include when you're embedding URLs that contain ampersands. Finally, even if the data only contains a few special characters but the data is very very long (the text of a chapter, say), it's nice to not have to be en/de-coding those few entities as you edit your xml file.

(我怀疑所有与评论的比较都有点误导/没有帮助。)

CDATA代表字符数据。您可以使用它来转义某些字符,否则这些字符将被视为常规XML。其中的数据将不会被解析。 例如,如果你想传递一个包含&的URL,你可以使用CDATA来实现。否则,您将得到一个错误,因为它将被解析为常规XML。

它用于包含可能被视为xml的数据,因为它包含某些字符。

这样,里面的数据将被显示,但不会被解释。

CDATA代表字符数据,这意味着这些字符串之间的数据包括可以解释为XML标记的数据,但不应该这样做。

CDATA和注释之间的主要区别是:

正如Richard指出的,CDATA仍然是文档的一部分,而注释不是。 在CDATA中不能包含字符串]]> (cend),而在注释中—是无效的。 在注释中不能识别参数实体引用。

这意味着从一个格式良好的文档中给出以下四个XML片段:

<!ENTITY MyParamEntity "Has been expanded">

<!--
Within this comment I can use ]]>
and other reserved characters like <
&, ', and ", but %MyParamEntity; will not be expanded
(if I retrieve the text of this node it will contain
%MyParamEntity; and not "Has been expanded")
and I can't place two dashes next to each other.
-->

<![CDATA[
Within this Character Data block I can
use double dashes as much as I want (along with <, &, ', and ")
*and* %MyParamEntity; will be expanded to the text
"Has been expanded" ... however, I can't use
the CEND sequence. If I need to use CEND I must escape one of the
brackets or the greater-than sign using concatenated CDATA sections.
]]>

<description>An example of escaped CENDs</description>
<!-- This text contains a CEND ]]> -->
<!-- In this first case we put the ]] at the end of the first CDATA block
     and the > in the second CDATA block -->
<data><![CDATA[This text contains a CEND ]]]]><![CDATA[>]]></data>
<!-- In this second case we put a ] at the end of the first CDATA block
     and the ]> in the second CDATA block -->
<alternative><![CDATA[This text contains a CEND ]]]><![CDATA[]>]]></alternative>