调用DocumentBuilderFactory.parse()返回Null Document的问题求助
DocumentBuilderFactory.parse() seem to return a null Document? First off, let's clear up a critical misunderstanding: DocumentBuilder.parse() will never return null. According to Java's official docs, this method either returns a valid Document object or throws an exception (like IOException, SAXException, etc.). The null you're seeing in your output is actually from dom.getElementById("1"), not the dom object itself.
Let's break down the issues and fixes step by step:
Why does
dom.getElementById("1")return null?- Your XML file doesn't have any element with an
id="1"attribute right now—your file only contains a single<address>element with no attributes at all. - Even if you added an
idattribute to the element, the DOM parser doesn't automatically recognize arbitraryidattributes as ID-type. To makegetElementById()work, you need to:- Add a DTD declaration to your XML to explicitly mark the
idattribute as an ID:<!DOCTYPE address [ <!ELEMENT address (#PCDATA)> <!ATTLIST address id ID #REQUIRED> ]> <address id="1">idk just filler for now</address> - Or enable validation in your parser configuration:
dbf.setValidating(true);
- Add a DTD declaration to your XML to explicitly mark the
- Your XML file doesn't have any element with an
Your
getTextValuecall has a logical errordom.getDocumentElement()returns the root element of your XML, which is already the<address>element. When you callgetTextValue(address, doc, "address"), you're trying to find a child<address>element inside the root<address>—which doesn't exist. That's why youraddressvariable ends up null.To get the text content of the root
<address>element directly, use:address = doc.getTextContent();Improve your exception handling
Right now you only print the exception message, which can be vague or empty in some cases. Print the full stack trace instead to catch hidden issues like file permission problems or XML encoding errors:
catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException se) { se.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); }
内容的提问来源于stack exchange,提问作者user9211520

