如何修改XML节点值? [英] how to modify xml node value?

查看:155
本文介绍了如何修改XML节点值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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.

这篇关于如何修改XML节点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆