问题
My strongest lead is that the code who deals with the incoming XMLs is actually receiving an invalid/incomplete file hence failing the DOM parsing. Any suggestions?
回答1:
Incomplete file is definitely the place to start looking. I'd print out the file right before the point you parse it to see what's getting sent to the parser. If it's incomplete it will be obvious. If it's invalid, you'll have a little searching to do.
回答2:
My first guess would be that the DOM-using code is treating elements that are marked as optional in the DTD as compulsory.
Edited to add: What I mean is that unless you validate against a DTD, you cannot expect something like the following (example using dom4j) to return anything but null.
doc.selectSingleNode("//some/element/in/a/structure");
The same is of course true if you're stringing element navigation calls together, or generally don't check return values before using them.
回答3:
You should have a stack trace pointing to where you NPE is thrown. That should narrow down the number of variables that can be null. Rather than getting the debugger or printf out, I suggest adding appropriate checks and throwing an exception where as soon as the error can be detected. It's a good habit to get into to avoid mysterious problems later.
回答4:
Ideally you should be running your java application inside a debugger, thus when an uncaught exception is thrown you can examine the callstack, variables, etc and see exactly what line caused the crash, and perhaps which data is null that got used.
If you can't use a debugger for whatever reason, then compile your application with debugging support, and add an exception handler for this particular error, and print out the stack trace. Again, this will show exactly what line in what file caused the crash.
来源:https://stackoverflow.com/questions/85370/most-common-cause-of-java-lang-nullpointerexception-when-dealing-with-xmls