javax.xml.parsers.DocumentBuilder悄然解析不可能?

时间:2014-01-08 17:02:45

标签: java xml dom

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,我不希望输出混乱。有没有办法让它沉默?

2 个答案:

答案 0 :(得分:4)

创建一个不执行任何操作的自定义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
    }
}

答案 1 :(得分:1)

尝试覆盖ErrorHandler

上的默认DocumentBuilder

作为JAXP的一部分,DOM之后的另一个选项是一组标准API,您始终可以尝试指定具有您正在寻找的行为的DOM解析器的替代实现。