Reputation: 1
Can anyone tell me how this code would result in a null document, but throw no exceptions?
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader("<?xml version=\"1.0\"?><company>test</company>")));
Originally:
private Document load(String message) throws MessagingException, IOException {
Document document = null;
try {
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(message.substring(message.indexOf(XML_BEGIN),
message.indexOf(XML_END)))));
}
catch (Exception e) {
e.printStackTrace();
}
...
Element element = document.getElementById(TIME_STAMP);
Results in:
java.lang.NullPointerException
at ...view.MailReceiver.parse(MailReceiver.java:156)
at ...view.MailReceiver.notify(MailReceiver.java:99)
at ...view.MailReceiver.main(MailReceiver.java:72)
Upvotes: 0
Views: 1121
Reputation: 3849
In your original code, I suspect the XML is badly formed due to the substrings being slightly "off".
When you're looking for your "XML_END" string then, assuming it's actually part of the XML you wish to parse (e.g. "" as a random example), you'll have to add on the length of this string also, or you'll missing part of your XML.
Also substring is exclusive on the endIndex so you might need a +1 in there too.
To start to check all this, I would assign the XML string (after substringing) into a variable and log it using log4j (or System.out.println) to see.
In your original code, if the parse exception occurs then you're dropping through to using the null document - not good! Possibly the cause of your NullPointerException. Usually you'd throw an exception in the catch block.
Upvotes: 0
Reputation: 20961
I don't see the document being null
.
// Parse XML into Document.
String xml = "<?xml version=\"1.0\"?><company>test</company>";
Document document = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
// Format Document to XML again.
StringWriter writer = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(writer));
System.err.println(writer);
Prints out
<?xml version="1.0" encoding="UTF-8" standalone="no"?><company>test</company>
so document
wasn't null.
Printing out document
gives you [#document: null]
, which might be a bit confusing because it mentions null
. This doesn't make document
itself null
, though.
Upvotes: 1