2011-07-07 29 views
6

我正在讀取SD卡上的xml文件。在這裏,我想改變的XML文件的值,我想將文件保存到SD卡..如何保存並更新xml文件中的值?

我的代碼如下....請指導我如何將XML文件保存到SD卡後更新值..

public void modifyNodeval(){ 
     try{ 
     DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 
     Document doc = docBuilder.parse(new File("/sdcard/sss.xml")); 

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

回答

1

事情是這樣的:

Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
StreamResult result = new StreamResult(file); 
DOMSource source = new DOMSource(doc); 
transformer.transform(source, result); 
0

此方法寫入了DOM文檔到文件的SD卡 如果你想在模擬器中測試它,確保你的AVD圖像是用SD卡圖像設置的(在圖像創建過程中完成)。

public static void writeXmlFile(Document doc, String filename) { 
    try { 
     // Prepare the DOM document for writing 
     Source source = new DOMSource(doc); 

     File file new File(Environment.getExternalStorageDirectory(),fileName); 

     Result result = new StreamResult(file); 

     // Write the DOM document to the file 
     Transformer xformer = TransformerFactory.newInstance().newTransformer(); 
     xformer.transform(source, result); 
    } catch (TransformerConfigurationException e) { 
     // handle exception 
    } catch (TransformerException e) { 
     // handle exception 
    } 
} 
相關問題