如何编辑xml文本值?

时间:2011-07-07 10:35:19

标签: android xml text

我想修改xml标签值的文本我使用了xml如下

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

这里我想更改名称 Jani as prasad 。我可以通过使用java代码来改变它吗

我编写了如下的java代码

 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();

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


         }
     }

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

2 个答案:

答案 0 :(得分:2)

您的代码中存在问题:“Jani”是父元素节点“from”的文本节点。所以你应该改变文本节点的值。

...
     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);
...

我认为RegExp对于此任务来说会容易得多

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

答案 1 :(得分:0)

有几个不同的例子可供选择。

Writing XML on Android这似乎是最好的样本。

其他点击: How to rewrite or modify XML in android 2.1 version

Load and modify xml file in Android