Ash*_*ish 34 java xml dom xml-parsing
使用Java DOM解析器解析XML文件会导致:
[Fatal Error] os__flag_8c.xml:103:135: An invalid XML character (Unicode: 0xc) was found in the element content of the document.
org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0xc) was found in the element content of the document.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
Run Code Online (Sandbox Code Playgroud)
jis*_*shi 40
即使将数据封装在CDATA块中,XML文档中也有一些不允许的字符.
如果您生成了文档,则需要对其进行实体编码或将其删除.如果您有错误的文档,则应在尝试解析之前删除这些字符.
请参阅此主题中的dolmens答案:XML中的无效字符
他链接到这篇文章:http://www.w3.org/TR/xml/#charsets
基本上,不允许低于0x20的所有字符,除了0x9(TAB),0xA(CR?),0xD(LF?)
小智 9
public String stripNonValidXMLCharacters(String in) {
StringBuffer out = new StringBuffer(); // Used to hold the output.
char current; // Used to reference the current character.
if (in == null || ("".equals(in))) return ""; // vacancy test.
for (int i = 0; i < in.length(); i++) {
current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)) ||
((current >= 0x10000) && (current <= 0x10FFFF)))
out.append(current);
}
return out.toString();
}
Run Code Online (Sandbox Code Playgroud)
每当无效的 xml 字符出现在 xml 中时,就会出现这样的错误。当你在记事本++中打开它时,它看起来像 VT、SOH、FF,这些都是无效的 xml 字符。我使用的是 xml 1.0 版,并且在按模式将文本数据输入数据库之前验证文本数据
Pattern p = Pattern.compile("[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u10000-\u10FFF]+");
retunContent = p.matcher(retunContent).replaceAll("");
Run Code Online (Sandbox Code Playgroud)
它将确保不会在 xml 中输入无效的特殊字符