将文档作为null [#document:null]使用DocumentBuilder在java中解析XML之后

Pra*_*eep 8 xml null document

在解析documengt之后,即使文档包含数据,我也会变为空.这是我的代码,我已将所有验证设置为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());
Run Code Online (Sandbox Code Playgroud)

回应如下:

doc:[#document: null]
Run Code Online (Sandbox Code Playgroud)

为什么?我错过了一些验证吗?

wja*_*ans 14

[#document: null]它只是您doc实例的toString ,它不会输出您的整个XML文档.

实例本身不为null,您可以继续处理而不会出现问题.