简体   繁体   中英

SAX parser load the DTD file

I have used the DOM parser before, put the DTD file under the project, the DOM code could detect the DTD file itself and parse the file based on the rules. While I transfer to the SAX parser, it seems the SAX parser couldn't detect the DTD file itself without setting. There are some posts mentioned to use resolveEntity() , while I couldn't understand very well. Could anyone help me to solve this problem to load a local DTD file to my java code in a simple way(in eclipse without CMD)?

If anyone could give a code example, it's the best.

I am posting a solution that works and i have taken inputs from SAX documentation. I have used the sample DTD and XML from W3 Schools for the same ( http://www.w3schools.com/xml/xml_dtd.asp ) , the DOCTYPE is not needed if it on a separate file hence removed that one line from the DTD. Not sure if it is the sample you wanted , hope it helps in some way !

public static void main(String[] args) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setValidating(true);

            XMLReader reader = factory.newSAXParser().getXMLReader();
            reader.parse(new InputSource(new FileInputStream("C:\\DevelopmentTools\\3.CODE\\SAX-XML.txt")));
            reader.setEntityResolver(new EntityResolver() {

                @Override
                public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                    // TODO Auto-generated method stub
                    if (systemId == null) {
                        systemId = "C:\\DevelopmentTools\\3.CODE\\99.WORKSPACE\\Note.dtd";
                    }
                    InputSource result = null;
                    result = new InputSource(systemId);
                    return result;
                }
            });

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM