Loading and parsing XML DOM documents.

Reading a 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 a 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();
  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"));

You have to create a class that implements ErrorHandler. When you set the error handler of the DocumentBuilder to your error handler, and parse documents, it will call the error, fatalError, or warning methods when some important errors arise.

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

Published: Sunday, 15 August 2004