如何从SD卡编辑现有XML文件的节点值并保存回去?

我想从SD卡编辑现有XML文件的节点值。

例如,如果我想编辑从山之旅海上旅行 RouteName的价值。

 <Trip> <RouteID>12345</RouteID> <RouteName>Mountain Trip</RouteName> </Trip> 

我尝试使用下面的代码,但它不影响SD卡上的XML文件。

 try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse( new File(Environment.getExternalStorageDirectory()+"/Trip/"+tripID+".trip")); Node nodes = doc.getElementsByTagName("RouteName").item(0); // newname is String variable which retrives value from edittext nodes.setNodeValue(newname); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult( new File(Environment.getExternalStorageDirectory()+"/Trip/"+tripID+".trip")); transformer.transform(source, result); } catch (Exception e) { e.printStackTrace(); } 

为什么SD卡上的XML文件没有被更新?

Solutions Collecting From Web of "如何从SD卡编辑现有XML文件的节点值并保存回去?"

我终于从这里得到了答案,谢谢斯密尔斯教授。

该修复程序是从nodes.setNodeValue更改为nodes.setTextContent

 try { String filePath = Environment.getExternalStorageDirectory()+"/Trip/"+tripID+".trip"; File file = new File(filePath); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(file); // Change the content of node Node nodes = doc.getElementsByTagName("RouteName").item(0); // I changed the below line form nodes.setNodeValue to nodes.setTextContent nodes.setTextContent(newname); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // initialize StreamResult with File object to save to file StreamResult result = new StreamResult(file); DOMSource source = new DOMSource(doc); transformer.transform(source, result); } catch (Exception e) { e.printStackTrace(); }