With the DTD location specified in the XML Document using a DOCTYPE declaration.
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware( true);
factory.setValidating( true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.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 {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware( true);
factory.setValidating( true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver( DTDEntityResolver( "file:test.dtd"));
Document document = builder.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 systemId = null;
private String substitute = null;
public DTDEntityResolver( String systemId, String substitute) {
this.systemId = systemId;
this.substitute = substitute;
}
public InputSource resolveEntity( String publicId, String systemId) throws SAXException, IOException {
if ( this.systemId.equals( systemId)) {
return new InputSource( substitute);
}
return null;
}
}