Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.xml.parsers.DocumentBuilder parse quietly not possible?

Tags:

java

dom

xml

The javax.xml.parsers.DocumentBuilder prints a message in std:err.

Example below:

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class FooMain {

    public static Document slurpXML(String s) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document rv = builder.parse(new ByteArrayInputStream(s.getBytes("UTF-8")));
        return rv;
    }

    public static void main(String args[]) throws Exception {
        try {
            slurpXML("foo");
        } catch (Exception e) {} // try to silence it - in vain
    }
}

Despite the try-catch block, running the program from the command line produces:

$ java -classpath dist/foo.jar FooMain 
[Fatal Error] :1:1: Content is not allowed in prolog.

I want to use DocumentBuilder in a console utility and I don't want the output to be cluttered. Is there a way to silence it?

like image 523
Marcus Junius Brutus Avatar asked Jan 08 '14 17:01

Marcus Junius Brutus


1 Answers

Create a custom ErrorHandler that does nothing

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class FooMain {

    public static Document slurpXML(String s) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {

            }

            @Override
            public void error(SAXParseException exception) throws SAXException {

            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {

            }
        });
        Document rv = builder.parse(new ByteArrayInputStream(s.getBytes("UTF-8")));
        return rv;
    }

    public static void main(String args[]) throws Exception {
        try {
            slurpXML("foo");
        } catch (Throwable e) {} // try to silence it - in vain
    }
}
like image 144
Liviu Stirb Avatar answered Sep 19 '22 04:09

Liviu Stirb