Search code examples
javadocumentdtd

Make DocumentBuilder.parse ignore DTD references


When I parse my xml file (variable f) in this method, I get an error

C:\Documents and Settings\joe\Desktop\aicpcudev\OnlineModule\map.dtd (The system cannot find the path specified)

I know I do not have the dtd, nor do I need it. How can I parse this File object into a Document object while ignoring DTD reference errors?

private static Document getDoc(File f, String docId) throws Exception{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(f);


    return doc;
}

Solution

  • A similar approach to the one suggested by @anjanb

        builder.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                if (systemId.contains("foo.dtd")) {
                    return new InputSource(new StringReader(""));
                } else {
                    return null;
                }
            }
        });
    

    I found that simply returning an empty InputSource worked just as well?