首页javadomJava HTML/XML - 如何使用javax.xml.parsers.DocumentBuilder进行静默解析

Java HTML/XML - 如何使用javax.xml.parsers.DocumentBuilder进行静默解析

我们想知道如何使用javax.xml.parsers.DocumentBuilder进行静默解析。
import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class Main {

  public static Document parse(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 {
      parse("foo");
    } catch (Throwable e) {
    }
  }
}