Q:

How to validate an XML file against a given DTD file?

I have an XML file, which has a DTD reference in it, like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE something SYSTEM "something.dtd">

I'm using a DocumentBuilderFactory:
public static Document validateXMLFile(String xmlFilePath) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setValidating(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    builder.setErrorHandler(new ErrorHandler() {
        @Override
        public void error(SAXParseException exception) throws SAXException {
            // do something more useful in each of these handlers
            exception.printStackTrace();
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            exception.printStackTrace();
        }

        @Override
        public void warning(SAXParseException exception) throws SAXException {
            exception.printStackTrace();
        }
    });
    Document doc = builder.parse(xmlFilePath);
    return doc;
}

But now I want to validate the XML file against a DTD file on a user-defined location, and not relative to the path of the XML file.
How can I do that?
Example:
validateXMLFile("/path/to/the/xml_file.xml", "/path/to/the/dtd_file.dtd");

A:

Use EntityResolver.
final String dtd = "/path/to/the/dtd_file.dtd"; 
builder.setEntityResolver(new EntityResolver() {
    public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
        if (systemId.endsWith("something.dtd")) {
            return new InputSource(new FileInputStream(dtd));
        }
        return null;
    }
});

Note that it can work only if the XML document has a DTD declaration.

