Parse an XML file with custom error handler

 
/*
An XML Document Containing a Simple Contact List
Start example

<?xml version="1.0" standalone="yes"?>

<folks>
   <person>
       <phone>306 555-9999</phone>
       <email>joe@webserver.net</email>
       <name>Wang, Joe</name>
   </person>
   <person>
       <phone>704 555-0000</phone>
       <name>Pet, Rob</name>
       <email>rob@server.com</email>
   </person>
</folks>

*/
  

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

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

public class Main {
  static public void main(String[] arg) throws Exception{
    String filename = "xmlFile.xml";
    boolean validate = false;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(validate);
    dbf.setNamespaceAware(true);

      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource(filename);
      Document doc = builder.parse(is);
  }
}

class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    show("Warning", e);
    throw (e);
  }

  public void error(SAXParseException e) throws SAXException {
    show("Error", e);
    throw (e);
  }

  public void fatalError(SAXParseException e) throws SAXException {
    show("Fatal Error", e);
    throw (e);
  }

  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() + " Column "
        + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}
Home 
  Java Book 
    Runnable examples  

XML DOM:
  1. Creating XML Element and add to Document
  2. Create and add Attribute to an Element
  3. Parse an XML File with DOM
  4. Parse an XML file with custom error handler
  5. Parse an XML string with DOM and StringReader.
  6. Visit all nodes from DOM
  7. Visit all nodes from DOM and output node type