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

时间:2012-01-24 02:29:52

标签: android xml dom

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

例如,如果我想将 Mountain Trip 中的RouteName值编辑为 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文件没有更新?

1 个答案:

答案 0 :(得分:10)

我终于得到了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();
}