如何修改XML节点值?

时间:2022-07-05 07:32:05

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

我是java应用程序的新开发人员。我想修改XML文件节点值。我已经使用xml文件进行修改,如下所示

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

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

在上面的xml中,我想将工资值更改为345375.对于此修改,我编写了如下代码

 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.

如果我用这种方式不改变薪水的价值。

How can I modify an XML node value?

如何修改XML节点值?

2 个解决方案

#1


0  

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.

首先,您必须意识到node.setValue()正在修改存储在内存中的表示。知道了,那么你只需要弄清楚如何将输出写入磁盘。看一下这个例子。

#2


0  

node.Text = "Enter your value here"; //This will work 

#1


0  

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.

首先,您必须意识到node.setValue()正在修改存储在内存中的表示。知道了,那么你只需要弄清楚如何将输出写入磁盘。看一下这个例子。

#2


0  

node.Text = "Enter your value here"; //This will work