简体   繁体   中英

Java DocumentBuilderFactory.parse(); returning null document

When I call DocumentBuilderFactory.parse(xml-file-path); , it returns a null document. I am 100% sure that the file path for the document is right.My full code is as follows:

public static boolean readXML(String xml) {
    Document dom;
    // Make an instance of the DocumentBuilderFactory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        // use the factory to take an instance of the document builder
        DocumentBuilder db = dbf.newDocumentBuilder();
        // parse using the builder to get the DOM mapping of the
        // XML file
        dom = db.parse(xml);

        System.out.println(dom + " " + xml + " " + dom.getElementById("1"));

        Element doc = dom.getDocumentElement();

        System.out.println(doc);

        address = getTextValue(address, doc, "address");
        System.out.println(address);
        return true;

    } catch (ParserConfigurationException pce) {
        System.out.println(pce.getMessage());
    } catch (SAXException se) {
        System.out.println(se.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    return false;
}

and

XMLReaderWriter.readXML("C:\\Users\\username\\eclipse-workspace\\project\\src\\preferences.xml");

Preferences.xml is simply:

<address>idk just filler for now</address>

The return I get is:

错误

Why is it returning a null document?

It doesn't give you a "null document", it gives you exactly the document you provided. address is your only element and is therefore treated as the document root element. The toString() method of your element object prints element name and element value. Since address is an element node, not a text node, the value is always null (element nodes don't have values, only child nodes). To get the contained text, you either have to get it's direct child, which is a pure text node, or use getTextContent().

System.out.println(doc);
System.out.println(doc.getFirstChild());
System.out.println(doc.getTextContent());

will print

[address: null]
[#text: idk just filler for now]
idk just filler for now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM