如何从SD卡编辑现有的XML文件的一个节点的值并保存它回来? [英] How to edit a node's value of an existing XML file from a SD card and save it back?
本文介绍了如何从SD卡编辑现有的XML文件的一个节点的值并保存它回来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编辑从SD卡现有的XML文件的一个节点的值。
I want to edit a node's value of an existing XML file from the SD card.
例如,如果我想从的山地旅的修改 RouteName
的值的海之旅的
For example if I want to edit RouteName
's value from Mountain Trip to Sea Trip.
<Trip>
<RouteID>12345</RouteID>
<RouteName>Mountain Trip</RouteName>
</Trip>
我尝试使用以下code,但它不会影响到SD卡上的XML文件。
I try to use the following code but it doesn't effect to the XML file on the SD card.
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文件中得到更新?
Why doesn't the XML file on the SD card get updated?
推荐答案
我终于从答案这里感谢ProfSmiles。
I finally got the answer from here, thanks ProfSmiles.
此修复程序是从 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();
}
这篇关于如何从SD卡编辑现有的XML文件的一个节点的值并保存它回来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文