Java HTML / XML How to - Report a missing DTD files








Question

We would like to know how to report a missing DTD files.

Answer

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
//w  ww. ja v  a 2s.c o m
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;

public class Main {

  // validate using DOM (DTD as defined in the XML)
  public static boolean validateWithDTDUsingDOM(String xml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);

    DocumentBuilder builder = factory.newDocumentBuilder();

    builder.setErrorHandler(new ErrorHandler() {
      public void warning(SAXParseException e) throws SAXException {
        System.out.println("WARNING : " + e.getMessage()); // do nothing
      }

      public void error(SAXParseException e) throws SAXException {
        System.out.println("ERROR : " + e.getMessage());
        throw e;
      }

      public void fatalError(SAXParseException e) throws SAXException {
        System.out.println("FATAL : " + e.getMessage());
        throw e;
      }
    });
    builder.parse(new InputSource(xml));
    return true;
  }

  // validate using SAX (DTD as defined in the XML)
  public static boolean validateWithDTDUsingSAX(String xml) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);

    SAXParser parser = factory.newSAXParser();
    XMLReader reader = parser.getXMLReader();
    reader.setErrorHandler(new ErrorHandler() {
      public void warning(SAXParseException e) throws SAXException {
        System.out.println("WARNING : " + e.getMessage()); // do nothing
      }

      public void error(SAXParseException e) throws SAXException {
        System.out.println("ERROR : " + e.getMessage());
        throw e;
      }

      public void fatalError(SAXParseException e) throws SAXException {
        System.out.println("FATAL : " + e.getMessage());
        throw e;
      }
    });
    reader.parse(new InputSource(xml));
    return true;
  }

  public static void main(String args[]) throws Exception {
    System.out.println(validateWithDTDUsingDOM("c:/temp/howto.xml"));
    System.out.println(validateWithDTDUsingSAX("c:/temp/howto.xml"));
  }
}