开发者

how to edit xml text value?

i would like modify text of xml tag value i have used an xml as follows

  <note>
       <to>Tove</to> 
       <from>Jani</from> 
       <heading>Reminder</heading> 
       <body>Don't forget me this weekend!</body> 
 </note>

here i would like to change the from name Jani as prasad.how can i chage that by using java code

i have written a java code as follows

 try{
     DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
     Document doc = docBuilder.parse(new File("/mnt/sdcard/one.xml"));

    //Get the staff element by tag name directly
     Node nodes = doc.getElementsByTagName("note").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("from".equals(nodes.getNodeName())){
             node.setNodeValue("prasad");

             TransformerFactory factory = TransformerFactory.newInstance();
             Transformer transformer = factory.newTransformer();

开发者_JAVA技巧             DOMSource source = new DOMSource(doc);
             StreamResult result = new StreamResult(new File("/mnt/sdcard/one.xml"));
             transformer.transform(source, result);


         }
     }

}
    catch (Exception e) {
        e.printStackTrace();
    }


There is problem in your code: "Jani" is a text node with parent element node "from". So you should change value of the text node.

...
     for (int i =0; i<list.getLength();i++) {
         Node node = list.item(i);

         //get the salary element, and update the value
         if("from".equals(node.getNodeName())){
             Text text = (Text) ((Element) node).getChildNodes().item(0);
             text.setNodeValue("prasad");
         }
     }

     TransformerFactory factory = TransformerFactory.newInstance();
     Transformer transformer = factory.newTransformer();

     DOMSource source = new DOMSource(doc);
     StreamResult result = new StreamResult(new File("/mnt/sdcard/one.xml"));
     transformer.transform(source, result);
...

And I think RegExp would be much easier for this task

"your xml as string".replaceAll("<from>.*?</from>", "<from>prasad</from>");


There are several different examples available.

Writing XML on Android This seems to have the best samples.

Other hits: How to rewrite or modify XML in android 2.1 version

Load and modify xml file in Android

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜