Android, org.w3c.dom: No validating DocumentBuilder implementation available

会有一股神秘感。 提交于 2019-12-23 18:07:43

问题


I'm trying to parse an XML document on Android 2.3.3, but it seems that there is no validating parser. The reason I need validation for is to ignore whitespaces in the XML file (blanks, carriage returns, line feeds, etc.).

Thats how I want to parse the document:

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setValidating(true);
dbfac.setIgnoringElementContentWhitespace(true);
DocumentBuilder docBuilder;
docBuilder = dbfac.newDocumentBuilder();
Document d = docBuilder.parse(file);

file is the URL to the file location as string. When executing the last line of this code the following exception is thrown:

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

When I take out dbfac.setValidating(true), no exception occurs, but then I have the problem with the whitespaces.

Does anyone know how to solve this problem? Do I have to use another parser?


回答1:


On Android, the implementation is hard coded to throw the exception when validation set set to true. Here is the 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;
}


来源:https://stackoverflow.com/questions/8370148/android-org-w3c-dom-no-validating-documentbuilder-implementation-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!