【发布时间】:2012-04-05 23:19:09
【问题描述】:
我正在用 Java 处理 xml,我有以下代码:
dbf.setValidating(false);
dbf.setIgnoringComments(false);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
DocumentBuilder db = null;
db = dbf.newDocumentBuilder();
db.setEntityResolver(new NullResolver());
_logger.error("Before processing the input stream");
processXml(db.parse(is));
其中 (is) 是一个 InputStream。
这会导致错误:
com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 2 字节 UTF-8 的第 2 字节无效
这听起来像是由于编码错误而导致的错误。我想在 InputStream 上设置编码,但我不确定如何。我找到了在 InputSource 或 InputStreamReader 上设置编码的方法,但是 db.parse 不采用 reader/InputSource。
解决此问题的最佳方法是什么?
谢谢!
【问题讨论】:
-
只有当您的 XML 格式错误(缺少编码信息)时才会发生这种情况。当您指定编码而不是让解析器通过定义明确的规则从文档中确定它时,事情往往会中断。当然,如果文档损坏,XML 解析器就不会读取它。 GIGO。
标签: java