Java HTML / XML How to - Use javax.xml.parsers.DocumentBuilder to parse quietly








Question

We would like to know how to use javax.xml.parsers.DocumentBuilder to parse quietly.

Answer

import java.io.ByteArrayInputStream;
/*w w  w .  j  a  va 2 s  . c om*/
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) {
    }
  }
}