我正在尝试在 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;
}
关于java - 安卓,org.w3c.dom : No validating DocumentBuilder implementation available,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8370148/