1
<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

4

2 回答 2

3

您需要键入每个节点以键入元素才能设置文本和属性。您可能想查看XPath,它简化了这样的事情。

import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        String xmlfile = "src/forum17753835/file.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(xmlfile);

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        Element element = (Element) xpath.evaluate("/root/program/params/param[@name='name2']", doc, XPathConstants.NODE);
        System.out.println(element.getTextContent());
    }

}
于 2013-07-19T19:31:47.103 回答
0
  NodeList params = doc.getElementsByTagName("param");
  for (int i = 0; i < params.getLength(); i++)
  {
     if (params.item(i).getAttributes().getNamedItem("name").getNodeValue().equals("name2"))
     {
        // do smth with element <param name='name2'>test2</param>
        // that is params.item(i) in current context
     }
  }
于 2013-07-19T19:36:19.107 回答