使用DocumentBuilder在Java中解析XML之后

使用DocumentBuilder在Java中解析XML之后

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

问题描述

解析文档之后,即使文档包含数据,我也将得到null.这是我的代码,我将所有验证都设置为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.

实例本身不为null,您可以毫无问题地继续进行处理.

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

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

08-31 08:54