如何从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文件没有被更新?

  • 允许用户在android调查/数据收集应用程序中创build表单
  • ImageButton中的透明背景有涟漪效应?
  • Android AutoCompleteTextViewpopup窗口显示后移动
  • 如何在Android中创build具有多列的表格?
  • 呈现问题无法parsingresource @ id / search_edit_frame
  • ConstraintLayout onMeasure非常慢
  • 如何将图像转换为base64string
  • Android更改材质高程阴影颜色
  • 我终于从这里得到了答案,谢谢斯密尔斯教授。

    该修复程序是从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(); }