gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:20:31 26 4
gpt4 key购买 nike

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

我得到的返回是:

error

为什么它返回空文档?

最佳答案

它不会为您提供“空文档”,它会准确地为您提供您所提供的文档。 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

关于Java DocumentBuilderFactory.parse();返回空文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48236491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com