How to prevent XML parsing errors being written to System.err (stderr)?

本秂侑毒 提交于 2019-12-23 06:49:01

问题


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.


回答1:


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;
    }
});


来源:https://stackoverflow.com/questions/7691585/how-to-prevent-xml-parsing-errors-being-written-to-system-err-stderr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!