gpt4 book ai didi

android - 如何从 SD 卡编辑现有 XML 文件的节点值并将其保存回来?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:23:55 28 4
gpt4 key购买 nike

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

例如,如果我想将 RouteName 的值从 Mountain Trip 编辑为 Sea Trip

<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 文件没有更新?

最佳答案

终于从here得到了答案,感谢 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();
}

关于android - 如何从 SD 卡编辑现有 XML 文件的节点值并将其保存回来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8981361/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com