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

<![CDATA[some stuff]]>

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

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


当前回答

其中包含的数据不会被解析为XML,因此不需要是有效的XML,或者可以包含看似XML但实际上不是的元素。

其他回答

它转义一个不能像往常一样传递给XML的字符串:

例子:

字符串中包含“&”。

你不能:

<FL val="Company Name">Dolce & Gabbana</FL>

因此,您必须使用CDATA:

<FL val="Company Name"> <![CDATA["Dolce & Gabbana"]]> </FL>

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

另一个例子是:

如果你有一个RSS提要(xml文档),并且想在描述的显示中包含一些基本的HTML编码,你可以使用CData对它进行编码:

<item>
  <title>Title of Feed Item</title>
  <link>/mylink/article1</link>
  <description>
    <![CDATA[
      <p>
      <a href="/mylink/article1"><img style="float: left; margin-right: 5px;" height="80" src="/mylink/image" alt=""/></a>
      Author Names
      <br/><em>Date</em>
      <br/>Paragraph of text describing the article to be displayed</p>
    ]]>
  </description>
</item>

RSS阅读器拉入描述并在CDATA中呈现HTML。

注意,不是所有的HTML标签都有效——我认为这取决于你使用的RSS阅读器。


解释一下为什么这个例子使用CData(而不是适当的pubData和dc:creator标签):这是用于使用RSS小部件的网站显示,我们没有真正的格式控制。

这使我们能够指定所包含图像的高度和位置,正确地格式化作者姓名和日期,等等,而不需要一个新的小部件。这也意味着我可以编写脚本,而不必手动添加它们。

它用于包含可能被视为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.

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