javax.xml.parsers.DocumentBuilder静默解析是不可能的吗?

Mar*_*tus 4 java xml dom

在中javax.xml.parsers.DocumentBuilder打印一条消息std:err

下面的例子:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

尽管有try-catch块,但从命令行运行程序仍会产生:

$ java -classpath dist/foo.jar FooMain 
[Fatal Error] :1:1: Content is not allowed in prolog.
Run Code Online (Sandbox Code Playgroud)

我想DocumentBuilder在控制台实用程序中使用,我不希望输出混乱。有没有办法让它沉默?

use*_*883 5

创建一个不执行任何操作的自定义ErrorHandler

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
    }
}
Run Code Online (Sandbox Code Playgroud)