有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

xml Java DocumentBuilderFactory。parse();返回空文档

当我调用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");

偏好。xml只是:

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

我得到的回报是:

error

它为什么返回空文档


共 (1) 个答案

  1. # 1 楼答案

    它不会给你一个“空文档”,它只会给你你提供的文档address是您唯一的元素,因此被视为文档根元素。元素对象的toString()方法打印元素名称和元素值。由于地址是元素节点,而不是文本节点,因此该值始终为(元素节点没有值,只有子节点)。要获取包含的文本,必须获取它的直接子节点(纯文本节点),或者使用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