Reputation: 5993
I am writing some unit tests that are deliberately passing bad strings to the Java DOM XML parser.
E.g.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
String message_xml = ""; // Empty string, not valid XML!!!
ByteArrayInputStream input = new ByteArrayInputStream(message_xml.getBytes());
Document doc = db.parse(input);
This is correctly throwing a SAXParseException (which is what my unit test expects). But it is also writing a message to System.err (stderr) in the Java console:
[Fatal Error] :1:1: Premature end of file.
Is there any way to configure the XML parser to NOT write to stderr?
I'm using Java 1.6SE.
Upvotes: 24
Views: 3136
Reputation: 288260
Install your own ErrorHandler
:
db.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException e) throws SAXException {
;
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
throw e;
}
@Override
public void error(SAXParseException e) throws SAXException {
throw e;
}
});
Upvotes: 35