gpt4 book ai didi

java - 调用获取 XML 元素返回 null

转载 作者:行者123 更新时间:2023-12-01 04:24:47 25 4
gpt4 key购买 nike

我正在查看一系列 XML 文件并从中获取特定元素。

 <key>A</key>

我正在使用这段代码来获取 XML 元素,但它返回 null 而不是我正在查找的元素。我无法更改 XML 文件。

    File key = new File(filePath);
PrintWriter keyWriter = new PrintWriter(key);

File xmlFile = new File(configPath);


DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlFile);
NodeList nodes = document.getElementsByTagName("key");


Element keyValue = (Element) nodes.item(0);
keyWriter.println(keyValue);
keyWriter.close();
}

我尝试过使用 document 方法以及 apache xmlconfiguration 和 getElementbyId 但到目前为止都返回 null。

最佳答案

我在您的代码中注意到您将元素对象传递给编写器的 println 函数,如下所示:

keyWriter.println(keyValue);

这将在文件中打印空值。尝试将其替换为:

keyWriter.println(keyValue.getTextContent());

关于java - 调用获取 XML 元素返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18596175/

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