2014-01-08 54 views
3

javax.xml.parsers.DocumentBuilderstd:err中打印消息。javax.xml.parsers.DocumentBuilder悄悄解析不可能?

實施例下面:

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

更通用的解決方案是重定向stderr – Taylor

回答

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