繁体   English   中英

Java DocumentBuilderFactory.parse(); 返回空文档

[英]Java DocumentBuilderFactory.parse(); returning null document

当我调用DocumentBuilderFactory.parse(xml-file-path); ,它返回一个空文档。 我100%确信文档的文件路径正确。我的完整代码如下:

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;
}

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

Preferences.xml很简单:

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

我得到的回报是:

错误

为什么返回空文档?

它不会为您提供“空文档”,它会为您提供您所提供的文档。 地址是您唯一的元素,因此被视为文档根元素。 元素对象的toString()方法显示元素名称和元素值。 由于address是元素节点,而不是文本节点,因此该值始终为null (元素节点没有值,只有子节点)。 要获取包含的文本,您必须获取它的直接子节点(即纯文本节点),或者使用getTextContent()。

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

将打印

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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