How to apply validation of local DTD file to xml file in java?

风格不统一 提交于 2019-12-05 10:46:20

Below is a sample that I believe could help to 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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!