我认为没有真正的区别。我更喜欢将 CDATA 用于所有内容,因为我不必关心要转义的字符,我唯一需要注意的是内容中的“]]>”,顺便说一句,如果您拆分 CDATA 开头,则允许使用并将结束标签分成多个片段。
示例(在 PHP 中)
<?php
function getXMLContent($content)
{
if
(
(strpos($content, '<') !== false) ||
(strpos($content, '>') !== false) ||
(strpos($content, '&') !== false) ||
(strpos($content, '"') !== false) ||
(strpos($content, '\'') !== false)
)
{
// If value contains ']]>', we need to break it into multiple CDATA tags
return "<![CDATA[". str_replace(']]>', ']]]]><![CDATA[>', $content) ."]]>";
}
else
{
// Value does not contain any special characters which needs to be wrapped / encoded / escaped
return $content;
}
}
echo getXMLContent("Hello little world!");
echo PHP_EOL . PHP_EOL;
echo getXMLContent("This < is > a & hard \" test ' for ]]> XML!");
?>
退货
Hello little world!
<![CDATA[This < is > a & hard " test ' for ]]]]><![CDATA[> XML!]]>
如果将其放入这样的 XML 结构中:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<test>
<![CDATA[This < is > a & hard " test ' for ]]]]><![CDATA[> XML!]]>
</test>
... 将其保存到文件(如 test.xml)并使用浏览器打开它,您会看到,浏览器(或任何其他 XML 应用程序/解析器)将向您显示正确的输出字符串:
This < is > a & hard " test ' for ]]> XML!