这几天在跟一个公司合作的项目中,对方提供了rss接口,通过这个接口,在我们网站展现出来,但是对方rss中出现了一些麻烦的字符,比如 &,®,™ 等。这些字符放到xml中,如果不做特殊处理,就会有错误产生。比如下面的xml:
<item>&</item>
在ie 浏览器,以及一些解析用的dom中解析这个片段,就会产生错误。
在w3c的技术规范中,也可以看到这样的字符不允许出现:
http://www.w3.org/tr/2001/rec-xml-c14n-20010315
比如:对 text nodes 允许的字符有如下要求: the string value, except all ampersands are replaced by &, all open angle brackets (< ) are replaced by <, all closing angle brackets (> ) are replaced by >, and all #xd characters are replaced by 
.
由于这些特殊字符比较多,我们在xml中替换的工作量比较大,我们可以在dtd文件中作些定义:
比如dtd文件中增加以下部分:
<!-- percent sign -->
<!entity amp "&#38;">
<!-- copyright sign -->
<!entity reg "®">
<!-- reg trade mark sign -->
<!entity trade "™">
并在xml中定义这个xml文件需要这个dtd支持:
<!doctype headcount system "eula.dtd">
这样在xml文件中出现 & ® ™ 这类特殊字符就不会再报错了。
有关更多的特殊字符可以参看:
http://xml.coverpages.org/courtdocument11-2002-05s-dtd.txt
那里罗列的特殊字符有近200个。
®