Android,org.w3c.dom:没有可用的验证DocumentBuilder实现

时间:2011-12-03 19:00:24

标签: java android xml dom xml-parsing

我正在尝试解析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是文件位置的字符串。执行此代码的最后一行时,抛出以下异常:

javax.xml.parsers.ParserConfigurationException: No validating DocumentBuilder implementation available

当我取出dbfac.setValidating(true)时,没有异常发生,但后来我遇到了空白的问题。

有谁知道如何解决这个问题?我是否必须使用其他解析器?

1 个答案:

答案 0 :(得分:3)

在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;
}