发现无效的 XML 字符(Unicode:0xc)

新手上路,请多包涵

使用 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)

原文由 Ashish 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

有一些字符在 XML 文档中是不允许的,即使您将数据封装在 CDATA 块中也是如此。

如果您生成了文档,则需要对其进行实体编码或剥离。如果你有一个错误的文档,你应该在尝试解析它之前去掉这些字符。

请参阅此线程中的 dolmens 答案: Invalid Characters in XML

他链接到这篇文章的地方:http: //www.w3.org/TR/xml/#charsets

基本上,0x20 以下的所有字符都是不允许的,除了 0x9 (TAB)、0xA (CR?)、0xD (LF?)

原文由 jishi 发布,翻译遵循 CC BY-SA 3.0 许可协议

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();
}

原文由 Dima 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题