javax.xml.parsers.DocumentBuilderstd: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
    }
}

尽管有 try-catch 块,从命令行运行程序会产生:
$ java -classpath dist/foo.jar FooMain
[Fatal Error] :1:1: Content is not allowed in prolog.

我想在控制台实用程序中使用 DocumentBuilder 并且我不希望输出困惑。有没有办法让它静音?

最佳答案

创建一个什么都不做的自定义 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
    }
}

关于javax.xml.parsers.DocumentBuilder 解析悄悄不可能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21001961/

10-11 03:43