Techie:Techie Main/Java/XML Parsing/Prevent DTD download
When parsing an XML document, here's how to create a DocumentBuilder which won't insist on downloading DTDs referenced in the documents it parses
private static DocumentBuilder documentBuilder;
static {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
documentBuilder = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException("Failed to create DocumentBuilder", e);
}
// required to stop the parser trying to download DTDs
EntityResolver resolver = new DefaultHandler(){
public org.xml.sax.InputSource resolveEntity(String publicId, String systemId)
throws org.xml.sax.SAXException, java.io.IOException {
return new org.xml.sax.InputSource(new java.io.StringReader(""));
}
};
documentBuilder.setEntityResolver(resolver);
}