簡體   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