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

After parsing the documengt document, I get zero, although the document contains data. Here is my code, I set all the checks 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 answer comes as:

 doc:[#document: null] 

Why? Is any check missing?

+7
source share
2 answers

[#document: null] is just the toString of your doc instance, it does not output your entire XML document.

The instance itself is not null, you may continue processing without problems.

+10
source

you have to add a static modifier to the Document object, I had the same problem, and after parsing, all non-static objects just referred to null. Creating statics somehow forces java to keep a reference to the created object during the parsing action in your variable.

-one
source

All Articles