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

问题描述 投票:0回答:12

使用 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)
java xml dom xml-parsing
12个回答
50
投票

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

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

请参阅支石墓在此线程中的回答:XML 中的无效字符

他链接到本文的位置:http://www.w3.org/TR/xml/#charsets

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


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

8
投票

每当 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("");

它将确保 xml 中不会输入无效的特殊字符


6
投票

字符 0x0C 在 XML 1.0 中无效,但在 XML 1.1 中却是 有效字符。因此,除非 xml 文件在序言中将版本指定为 1.1,否则它就是无效的,您应该向该文件的制作者投诉。


4
投票

您可以使用自定义 FilterReader 类过滤所有“无效”字符:

public class InvalidXmlCharacterFilter extends FilterReader {

    protected InvalidXmlCharacterFilter(Reader in) {
        super(in);
    }

    @Override
    public int read(char[] cbuf, int off, int len) throws IOException {
        int read = super.read(cbuf, off, len);
        if (read == -1) return read;

        for (int i = off; i < off + read; i++) {
            if (!XMLChar.isValid(cbuf[i])) cbuf[i] = '?';
        }
        return read;
    }
}

然后像这样运行:

InputStream fileStream = new FileInputStream(xmlFile);
Reader reader = new BufferedReader(new InputStreamReader(fileStream, charset));
InvalidXmlCharacterFilter filter = new InvalidXmlCharacterFilter(reader);
InputSource is = new InputSource(filter);
xmlReader.parse(is);

3
投票

在 UTF-8 上,不允许使用这些范围内的所有代码,对于 XML 1.0:

  • 0..8
  • B..C
  • E..1F
  • D800..DFFF
  • FFFE..FFFF

可以删除的正则表达式是:

text.replaceAll('[\\x{0}-\\x{8}]|[\\x{B}-\\x{C}]|[\\x{E}-\\x{1F}]|[\\x{D800}-\\x{DFFF}]|[\\x{FFFE}-\\x{FFFF}]', "")

注意:如果您使用 XML 1.1,您还需要删除这些间隔:

  • 7F..84
  • 86..9F

参考资料:


1
投票

我刚刚使用了这个项目,发现它非常方便:https://github.com/rwitzel/streamflyer

使用 InvalidXmlCharacterModifier,如文档所述。

就像这个例子:

public String stripNonValidXMLCharacters(final String in) {

  final Modifier modifier = new InvalidXmlCharacterModifier("",
    InvalidXmlCharacterModifier.XML_10_VERSION);

  final ModifyingReader modifyingReader = 
         new ModifyingReader(new StringReader(in), modifier);

  return IOUtils.toString(modifyingReader);
}

0
投票

我遇到了类似的问题,XML 包含控制字符。查看代码后,我发现使用了一个已弃用的类 StringBufferInputStream 来读取字符串内容。

http://docs.oracle.com/javase/7/docs/api/java/io/StringBufferInputStream.html

This class does not properly convert characters into bytes. As of JDK 1.1, the preferred way to create a stream from a string is via the StringReader class.

我将其更改为 ByteArrayInputStream 并且工作正常。


0
投票

对于将字节数组读入字符串并尝试使用 JAXB 转换为对象的人,您可以通过从字节数组创建字符串来添加“iso-8859-1”编码,如下所示:

String JAXBallowedString= new String(byte[] input, "iso-8859-1");

这会将冲突的字节替换为 JAXB 可以处理的单字节编码。显然这个解决方案只是解析xml。


0
投票

所有这些答案似乎都假设用户正在生成错误的 XML,而不是从 gSOAP 接收它,gSOAP 应该更清楚!


0
投票

今天,我也遇到了类似的错误:

Servlet.service() for servlet [remoting] in context with path [/***] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: buildDocument failed.] with root cause
org.xml.sax.SAXParseException; lineNumber: 19; columnNumber: 91; An invalid XML character (Unicode: 0xc) was found in the value of attribute "text" and element is "label".


在我第一次遇到错误后,我手动重新输入了整行,这样特殊字符就无法潜入,并且Notepad ++没有显示任何不可打印的字符(白底黑字) ,尽管如此,我一遍又一遍地遇到同样的错误。

当我查找我所做的与前辈不同的事情时,结果发现它是在结束 /> 之前的一个额外空格(正如我听说的那样,建议旧的解析器使用,但无论如何它不应该有任何区别) ,根据 XML 标准):

<label text="this label's text" layout="cell 0 0, align left" />

当我删除空格时:

<label text="this label's text" layout="cell 0 0, align left"/>

一切都很好。


所以这绝对是一个误导性的错误消息。


0
投票

org.xml.sax.SAXParseException 包含现有的无效字符行号和列号。

用于捕获和记录此详细信息:

try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream inputStream = new FileInputStream(path);
        Document document = builder.parse(inputStream);

    } catch (SAXParseException e) {
        logger.error("Xml parse error, cause of the line number: {}, column number: {} .", e.getLineNumber(), e.getColumnNumber(), e);
    }
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.