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

前端 未结 4 1621
陌清茗
陌清茗 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:23

    You can also ignore the DTD altogether: http://marcels-javanotes.blogspot.com/2005/11/parsing-xml-file-without-having-access.html

    0 讨论(0)
  • 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"));
    
    0 讨论(0)
  • 2020-12-17 20:36

    I used the custom EntityResolver like the example above but it still searched the DTD file in another base directory. So I debuged it and then found out I need to change user.dir system property. So I added this line to my application initialization method and it works now.

    System.setProperty("user.dir")
    
    0 讨论(0)
  • 2020-12-17 20:41

    Below code work for me, It ignore DTD

    Imports:

    import java.io.ByteArrayInputStream;
    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.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.EntityResolver;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    

    Code :

    File fileName = new File("XML File Path");
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    EntityResolver resolver = new EntityResolver () {
    public InputSource resolveEntity (String publicId, String systemId) {
    String empty = "";
    ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
                        System.out.println("resolveEntity:" + publicId + "|" + systemId);
                        return new InputSource(bais);
                        }
                        };
    documentBuilder.setEntityResolver(resolver); 
    Document document = documentBuilder.parse(fileName);
    
    0 讨论(0)
提交回复
热议问题