这是一个具体示例,说明为什么/何时可能要使用 CDATA。
去掉 CDATA,这个简单的 SVG 将无法被浏览器解析:
<?xml version="1.0" encoding="UTF-8"?>
<svg version="1.1"
baseProfile="full"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:ev="http://www.w3.org/2001/xml-events"
>
<title>CDATA</title>
<style type="text/css"><![CDATA[
/**
* Imagine you mention this element <foo> in a comment… or use the & sign.
* Then…
*
* If this weren't wrapped into CDATA (mind both the starting and closing
* tags), then the browser would fail to parse the file correctly. For example:
*
* Firefox would fail with this:
* > XML Parsing Error: mismatched tag. Expected: [foo's closing tag].
*
* Chrome and Safari would fail with this:
* > This page contains the following errors:
* > error on line 22 at column 9: Opening and ending tag mismatch: foo line 0 and style
*/
]]></style>
<text x="20" y="60" font-size="60">Hello</text>
<script><![CDATA[
// <text>
// see comment in the CSS, because it's the same situation here.
]]></script>
</svg>
这是针对 SVG 文件的,但您应该对任何 XML 文件采取相同的预防措施。