Java – How do I apply validation of a local DTD file to an xml file in Java?

How do I apply validation of a local DTD file to an xml file in Java?… here is a solution to the problem.

How do I apply validation of a local DTD file to an xml file in Java?

I need to parse a bunch of incoming XML documents, but it doesn’t contain DTD declarations. Currently I am parsing xml documents using the SAX parser, but there is no DTD validation. Now I want to apply DTD validation. The DTD was created by myself. How do I validate an XML file using a DTD (SAX parser) that I created? I’ve found some tutorials for using the Transformer, but all for DOM Parser.

How to use the SAX parser to parse XML files and apply DTD validation.
Any help….

Best Solution

Here’s an example that I believe will help you do what you want:

private void loadXML(Reader reader) throws ParserConfigurationException, SAXException {
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    parserFactory.setValidating(true);
    SAXParser parser = parserFactory.newSAXParser();
    parser.parse(new InputSource(reader), new MyHandler());
}

private static class MyHandler
        extends DefaultHandler {

    private static final String PREFS_DTD_URI = "http://www.example.com/dtd/document.dtd";

    public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
        if (systemId.equals(PREFS_DTD_URI)) {
            InputSource is = new InputSource(new StringReader(PREFS_DTD));  // PREFS_DTD is a string containing actual DTD, any other Reader could be here
            is.setSystemId(PREFS_DTD_URI);
            return is;
        }
        // else use the default behaviour
        return null;
    }
}

Related Problems and Solutions