xml的某个标签中的值包含了&,会报下面的错误
Unescaped & or nonterminated character/entity reference
网上流传的解决方法如下:
用&代替&
但是stackoverflow上有个小哥表示自己不想这么干,就发了个帖子:《我一定要用&替换&符号吗》
下面是大佬的回复:
Yes. Just as the error said, in HTML, attributes are #PCDATA meaning they’re parsed. This means you can use character entities in the attributes. Using & by itself is wrong and if not for lenient browsers and the fact that this is HTML not XHTML, would break the parsing. Just escape it as & and everything would be fine.
HTML5 allows you to leave it unescaped, but only when the data that follows does not look like a valid character reference. However, it’s better just to escape all instances of this symbol than worry about which ones should be and which ones don’t need to be.
Keep this point in mind; if you’re not escaping & to &, it’s bad enough for data that you create (where the code could very well be invalid), you might also not be escaping tag delimiters, which is a huge problem for user-submitted data, which could very well lead to HTML and script injection, cookie stealing and other exploits.
Please just escape your code. It will save you a lot of trouble in the future.
补充:这个错误的本质是"裸的 &"
原文讲的是 XML 里的 Unescaped or nonterminated character entity reference。这个报错只有一种根因:正文里出现了 &,但不是合法实体(&、< 这种)的开头。
最常见的三种场景:
- URL 里的参数没转义:
<link>https://example.com/?a=1&b=2</link>—— 这里的&b会被当成实体开头。 - 手写
&又忘了分号: 少了;。 - 中文标点被误输入:全角
&其实没问题,但复制粘贴时常混进半角。
修法就是转义成 &。命令行快速定位:
xmllint --noout 文件.xml
会直接给出行号,比在浏览器里看一片红快得多。批量检查一个目录:
find . -name "*.xml" -exec xmllint --noout {} \;
本文整理于 2017 年,2026 年 11 月补写。