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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With