开发者

How to modify XML node value?

开发者 https://www.devze.com 2023-03-17 16:37 出处:网络
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

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.newDocu开发者_如何学PythonmentBuilder();
     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?


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.Text = "Enter your value here"; //This will work 
0

精彩评论

暂无评论...
验证码 换一张
取 消