如何修改XML节点值?节点、XML

2023-09-04 12:07:42 作者:逆水寒

我在Java的application.i新的开发人员想修改valuse.i使用了一个XML文件,如下所示修改xml文件节点

i am new developer in java application.i would like to modify an xml file node valuse.i have used an xml file for modify as follows

      <staff id="2">
           <firstname>yong</firstname>
           <lastname>mook kim</lastname>
           <nickname>mkyong</nickname>
           <salary>2000000</salary>
           <age>28</age>
       </staff>

在上面的XML我想改变薪酬值345375.for此修改我写code如下:

in above xml i would like to change salary value as 345375.for this modification i have written code as follows

         try{
     DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
     Document doc = docBuilder.parse(new File("/sdcard/myxml.xml"));

    //Get the staff element by tag name directly
     Node nodes = doc.getElementsByTagName("staff").item(0);
    //loop the staff child node
     NodeList list = nodes.getChildNodes();

     for (int i =0; i<list.getLength();i++){
         Node node = list.item(i);

         //get the salary element, and update the value
         if("salary".equals(node.getNodeName())){
             node.setNodeValue("345375");



         }
     }
}
    catch (Exception e) {
        e.printStackTrace();
    }

如果我用这种方式该值不修改工资。

if i use this way that value not modifying salary.

我该如何修改XML节点值?

how can i modify an xml node value?

请人帮我。

在此先感谢

推荐答案

首先,你必须认识到, node.setValue()正在修改重新presentation的存储的内存的。知道了这一点,那么你只需要弄清楚如何写输出到磁盘。请参见这个,对于一个例子。

First you have to realize that node.setValue() is modifying the representation that is stored in memory. Knowing that, then you just need to figure out how to write that output to disk. See this, for an example.