SAXParserFactory DTD Validation

With the DTD location specified in the XML Document using a DOCTYPE declaration.

try {
  SAXParserFactory factory = SAXParserFactory.newInstance();
  factory.setNamespaceAware( true);
  factory.setValidating( true);

  XMLReader reader = parser.getXMLReader();
  reader.parse( new Inputsource( "test.xml"));

} catch ( ParserConfigurationException e) {
  e.printStackTrace();
} catch ( SAXException e) {
  e.printStackTrace();
} catch ( IOException e) {
  e.printStackTrace();
}
			

With the DTD location specified using a bespoke entity resolver (only works if a DOCTYPE with a systemId has been specified in the document).

try {
  SAXParserFactory factory = SAXParserFactory.newInstance();
  factory.setNamespaceAware( true);
  factory.setValidating( true);

  XMLReader reader = parser.getXMLReader();
  reader.setEntityResolver( DTDEntityResolver( "file:test.dtd"));

  reader.parse( new Inputsource( "test.xml"));

} catch ( ParserConfigurationException e) {
  e.printStackTrace();
} catch ( SAXException e) {
  e.printStackTrace();
} catch ( IOException e) {
  e.printStackTrace();
}

public static class DTDEntityResolver implements EntityResolver {
  private String newSystemId = null;
  boolean firstPass = true;

  public DTDEntityResolver( String systemId) {
    this.newSystemId = systemId;
  }

  public InputSource resolveEntity( String publicId, String systemId) throws SAXException, IOException {
    InputSource result = null;
    
    if ( firstPass) {
      result = new InputSource( newSystemId);
    } else {
      result = new InputSource( systemId);
    }
    
    firstPass = false;

    return result;
  }
}