Loading and parsing XML DOM documents in Java

Published: Sunday, 15 August 2004

Reading an XML document from file

Use the following snippet of code.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(new File("test.xml"));

Validating an XML document while parsing

When you parse a document, you can validate it against a DTD at the same time.

  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setValidating(true);
  DocumentBuilder db = dbf.newDocumentBuilder();

Custom Error Handler

class TestErrorHandler implements ErrorHandler {
    private ArrayList al;
    public TestErrorHandler() {
      al = new ArrayList();
    }
    public void error(SAXParseException exception) throws SAXException {
      al.add(exception);
    }

    public void fatalError(SAXParseException exception) throws SAXException {
      al.add(exception);
    }

    public void warning(SAXParseException exception) throws SAXException {
      al.add(exception);
    }
    public boolean hasErrors() {
      return !al.isEmpty();
    }
    public void printErrors(PrintStream out) {
      for (int i=0; i<al.size(); i++) {
        SAXParseException spe = (SAXParseException) al.get(i);
        out.println(spe.getSystemId() + ":" + spe.getLineNumber() + "," + spe.getColumnNumber());
        out.println(new StringBuffer().append(spe.getLocalizedMessage()).toString());
      }
    }
  }
}
...

  TestErrorHandler teh = new TestErrorHandler();
  db.setErrorHandler(teh);
  doc = db.parse(new File("test.xml"));

Create a class that implements ErrorHandler.

Then set an instance of your error handler into the DocumentBuilder and parse documents. The error, fatalError, or warning methods will be called when important errors arise.

In the case above I’ve saved them up to be printed later on.