【发布时间】:2013-07-19 04:42:46
【问题描述】:
<root>
<program name="SomeProgramName">
<params>
<param name='name'>test</param>
<param name='name2'>test2</param>
</params>
</program>
</root>
我有上面的 xml 文档。我需要将 test 的值更改为新值
我在 xml 文档中读为
String xmlfile = "path\\to\\file.xml"
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlfile);
//get the params element
Node params = doc.getElementsByTagName("params").item(0);
//get a list of nodes in the params element
NodeList param = params.getChildNodes();
这就是我卡住的地方。我找不到通过“名称”设置参数之一的值的方法
我使用的是 java 1.7
【问题讨论】:
-
我建议对它使用 XPath 查询。语法类似于
/root/program/params/param[@name='name2']。有关 xpath 设置,请参阅 this question