3

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?

Kevin
  • 53,822
  • 15
  • 101
  • 132
Marc
  • 257
  • 1
  • 7
  • I just found a post on google-code that indicates that XML validation is not implemented: [link](https://code.google.com/p/android/issues/detail?id=7395) This post is 1,5 years old and I don't know if something has changed already. Is there another parser that implements XML-validation or that is capable to ignore whitespaces? – Marc Dec 04 '11 at 10:04

1 Answers1

3

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;
}
Chuck Krutsinger
  • 2,830
  • 4
  • 28
  • 50