How to modify XML node value?

2019-03-14 04:01发布

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

  <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

 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?

2条回答
我只想做你的唯一
2楼-- · 2019-03-14 04:49

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.

查看更多
疯言疯语
3楼-- · 2019-03-14 04:56
node.Text = "Enter your value here"; //This will work 
查看更多
登录 后发表回答