【发布时间】:2014-11-29 05:12:53
【问题描述】:
我必须解析一个包含许多名称值对的 xml 文件。 如果它与给定名称匹配,我必须更新该值。 我选择了 DOM 解析,因为它可以轻松遍历任何部分并且可以快速更新值。 但是,当我在示例文件上运行它时,它会给我一些有线结果。
我是 DOM 新手,所以如果有人可以帮助它可以解决我的问题。 我尝试了各种方法,但都导致内容为空值或#text 节点名称。 我无法获取标签的文本内容。
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlFilePath);
//This will get the first NVPair
Node NVPairs = document.getElementsByTagName("NVPairs").item(0);
//This should assign nodes with all the child nodes of NVPairs. This should be ideally
//<nameValuePair>
NodeList nodes = NVPairs.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
// I think it will consider both starting and closing tag as node so checking for if it has
//child
if(node.hasChildNodes())
{
//This should give me the content in the name tag.
//However this is not happening
if ("Tom".equals(node.getFirstChild().getTextContent())) {
node.getLastChild().setTextContent("2000000");
}
}
}
示例 xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><application>
<NVPairs>
<nameValuePair>
<name>Tom</name>
<value>12</value>
</nameValuePair>
<nameValuePair>
<name>Sam</name>
<value>121</value>
</nameValuePair>
</NVPairs>
【问题讨论】: