Java-Android,org.w3c.dom:没有可用的验证DocumentBuilder实现
作者:互联网
我正在尝试在Android 2.3.3上解析XML文档,但似乎没有验证解析器.我需要进行验证的原因是忽略XML文件中的空格(空白,回车,换行等).
那就是我想解析文档的方式:
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setValidating(true);
dbfac.setIgnoringElementContentWhitespace(true);
DocumentBuilder docBuilder;
docBuilder = dbfac.newDocumentBuilder();
Document d = docBuilder.parse(file);
file是文件位置的URL,为字符串.执行此代码的最后一行时,将引发以下异常:
javax.xml.parsers.ParserConfigurationException: No validating DocumentBuilder implementation available
当我取出dbfac.setValidating(true)时,没有异常发生,但是空白出现了问题.
有谁知道如何解决这个问题?我必须使用另一个解析器吗?
解决方法:
在Android上,当验证设置为true时,对实现进行硬编码以引发异常.这是Android source code link:
@Override
public DocumentBuilder newDocumentBuilder()
throws ParserConfigurationException {
if (isValidating()) {
throw new ParserConfigurationException(
"No validating DocumentBuilder implementation available");
}
/**
* TODO If Android is going to support a different DocumentBuilder
* implementations, this should be wired here. If we wanted to
* allow different implementations, these could be distinguished by
* a special feature (like http://www.org.apache.harmony.com/xml/expat)
* or by throwing the full SPI monty at it.
*/
DocumentBuilderImpl builder = new DocumentBuilderImpl();
builder.setCoalescing(isCoalescing());
builder.setIgnoreComments(isIgnoringComments());
builder.setIgnoreElementContentWhitespace(isIgnoringElementContentWhitespace());
builder.setNamespaceAware(isNamespaceAware());
// TODO What about expandEntityReferences?
return builder;
}
标签:dom,xml,java,android,xml-parsing 来源: https://codeday.me/bug/20191202/2085220.html