12

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?

Mat
  • 202,337
  • 40
  • 393
  • 406
Pradeep
  • 131
  • 1
  • 2
  • 4
  • I think this link can answer of your question. http://stackoverflow.com/questions/2018868/documentbuilder-parseinputstream-returns-null – Ishwar Pohani Oct 31 '12 at 05:46

2 Answers2

16

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

Joel Fischer
  • 6,521
  • 5
  • 35
  • 46
wjans
  • 10,009
  • 5
  • 32
  • 43
-1

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.