1

我正在查看一系列 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();  
}

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

4

1 回答 1

0

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

keyWriter.println(keyValue);

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

keyWriter.println(keyValue.getTextContent());
于 2013-09-03T18:03:48.270 回答