// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ValidateDTD {
    public static void testDTD(final String xmlfnm, final String dtdfnm) throws SAXException, IOException, ParserConfigurationException {
        System.out.printf("Validating %s against DTD %s\n", xmlfnm, dtdfnm);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ErrorHandler() {
            public void error(SAXParseException ex) throws SAXException {
                System.out.println(ex.getMessage());
            }
            public void fatalError(SAXParseException ex) throws SAXException {
                System.out.println(ex.getMessage());
            }
            public void warning(SAXParseException ex) throws SAXException {
                System.out.println(ex.getMessage());
            }
        });
        db.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                return new InputSource(dtdfnm);
            }
        });
        Document doc = db.parse(new File(xmlfnm));
    }
    public static void main(String[] args) throws Exception {
        testDTD("test1.xml", "test.dtd");
        testDTD("test2.xml", "test.dtd");
        testDTD("test3.xml", "test.dtd");
    }
}
