3

I have the following Java method:

private static Document documentFromFile(final File xmlFile)
{
    Document document = null;
    try
    {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
            .newInstance();
        DocumentBuilder docBuilder = docBuilderFactory
            .newDocumentBuilder();
        document = docBuilder.parse(xmlFile);
        document.getDocumentElement().normalize();
    }
    catch(Exception exc)
    {
        // Handle exception...
    }

    return document;
}

In my test methods, if I pass this method a malformed XML file I get all sorts of error output on my console:

[Fatal Error] :1:1: Content is not allowed in prolog.

[Fatal Error] :1:1: Premature end of file.

I assume the culprit is docBuilder.parse(xmlFile). I'd like to be able to disable this default output and "silence" the document builder, and I don't see any setter methods on this object that allow me to do anything like that. Do I have an remedies here or am I stuck with this?

Community
  • 1
  • 1
IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756
  • Which [implementation](http://www.jarfinder.com/index.php/java/info/org.w3c.dom.Document) of DOM manipulation library are we talking about? And what version? DocumentBuilderFactory has a setAttribute method, but you have to know what property name to set. – Flavio Cysne Jun 04 '12 at 16:34
  • See if apply to you: ["how to disable dtd at runtime in java's xpath?"](http://stackoverflow.com/q/243728/1322198) and ["How can I ignore DTD validation but keep the Doctype when writing an XML file?"](http://stackoverflow.com/q/582352/1322198) – Flavio Cysne Jun 04 '12 at 16:37
  • I'm using `javax.xml.parsers.*` for the lib and am using XSD schema validation... – IAmYourFaja Jun 04 '12 at 17:48

1 Answers1

3

Use DocumentBuilder.setErrorHandler to set an implementation of ErrorHandler. Don't be confused by the package name. Even though it says "org.xml.sax" it is they one you want. I think you can just use DefaultHandler because the Javadoc says that it ignores errors and warnings. If it is still too verbose, you can just supply your own implementation.

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
db.setErrorHandler(new DefaultHandler());
John Watts
  • 8,717
  • 1
  • 31
  • 35