4

我是 Java 应用程序的新开发人员。我想修改一个 XML 文件节点值。我使用了一个xml文件进行如下修改

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

在上面的 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();
    }

如果我以这种方式使用该值不会修改薪水。

如何修改 XML 节点值?

4

2 回答 2

1

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

于 2011-07-04T13:16:08.227 回答
0
node.Text = "Enter your value here"; //This will work 
于 2011-07-30T01:33:42.723 回答