获取文档为空 [#document: null] 使用 DocumentBuilder 在 java 中解析 XML 后 [英] Getting document as null [#document: null] After parsing XML in java using DocumentBuilder

查看:29
本文介绍了获取文档为空 [#document: null] 使用 DocumentBuilder 在 java 中解析 XML 后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解析文档后,我得到了空值,即使文档包含数据.这是我的代码,我已将所有验证设置为 false.

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());

响应如下:

doc:[#document: null]

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

Why? Am I missing some validation?

推荐答案

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

[#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.

这篇关于获取文档为空 [#document: null] 使用 DocumentBuilder 在 java 中解析 XML 后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆