Getting document as null [#document: null] After parsing XML in java using DocumentBuilder

雨燕双飞 提交于 2020-04-03 04:27:42

问题


After parsing the documengt I am getting null, even though the document contains data. Here is my code, I have set all validations to false.

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

    domFactory.setNamespaceAware(false); // never forget this!
    domFactory.setCoalescing(false);
    domFactory.setValidating(false);
    domFactory.setFeature("http://xml.org/sax/features/namespaces", false);
    domFactory.setFeature("http://xml.org/sax/features/validation", false);
    domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    domFactory.setFeature("http://apache.org/xml/features/allow-java-encodings",
                       true);



    DocumentBuilder builder = domFactory.newDocumentBuilder();

    builder.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(java.lang.String publicId, java.lang.String systemId)
                throws SAXException, java.io.IOException {
            if (publicId.equals("--myDTDpublicID--"))
                // this deactivates the open office DTD
                return new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
            else return null;
        }
    });


    Document doc = null;
    URL url = new URL(urlStr);
    URLConnection urlc = url.openConnection();



    doc = builder.parse(urlc.getInputStream());
    System.out.println("doc:" + doc.toString());

The response comes as :

doc:[#document: null]

Why? Am I missing some validation?


回答1:


[#document: null] is just the toString of your doc instance, it doesn't output your whole XML document.

The instance itself is not null, you can probably continue your processing without a problem.




回答2:


you should add the static modifier to your Document object, I had the same problem and after the parsing action all non-static objects were simply referring to null. Making it static somehow forces java to keep the reference to the created object during the parse action in your variable.



来源:https://stackoverflow.com/questions/5694600/getting-document-as-null-document-null-after-parsing-xml-in-java-using-docum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!