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
}
}
尽管有try-catch块,但从命令行运行程序会产生:
$ java -classpath dist/foo.jar FooMain
[Fatal Error] :1:1: Content is not allowed in prolog.
我想在控制台实用程序中使用DocumentBuilder
,我不希望输出混乱。有没有办法让它沉默?
答案 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解析器的替代实现。