Parsing an XML file with a DTD schema on a relative path

前端 未结 4 1634
陌清茗
陌清茗 2020-12-17 20:02

I have the following java code:


DocumentBuilder db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=db.parse(new File(\"/opt/myfile\         


        
4条回答
  •  盖世英雄少女心
    2020-12-17 20:35

    You need to use a custom EntityResolver to tweak the path of the DTD so that it can be found. For example:

    db.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId)
                throws SAXException, IOException {
            if (systemId.contains("schema.dtd")) {
                return new InputSource(new FileReader("/path/to/schema.dtd"));
            } else {
                return null;
            }
        }
    });
    

    If schema.dtd is on your classpath, you can just use getResourceAsStream to load it, without specifying the full path:

    return new InputSource(Foo.class.getResourceAsStream("schema.dtd"));
    

提交回复
热议问题