如何保存&更新xml文件中的值?

时间:2011-07-07 06:03:21

标签: android saxparser

我正在从SD卡读取xml文件。在这里,我想更改XML文件的值,我想将文件保存到SD卡..

我的代码如下所示....请指导我在更新值后如何将XML文件保存到SD卡。

public void modifyNodeval(){
        try{
         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
         Document doc = docBuilder.parse(new File("/sdcard/sss.xml"));

        //Get the staff element by tag name directly
         Node nodes = doc.getElementsByTagName("Employee").item(0);
        //loop the staff child node
         NodeList list = nodes.getChildNodes();

         for (int i =0; i<list.getLength();i++){
             Node node = list.item(i);

             //get the salary element, and update the value
             if("Emp_Name".equals(node.getNodeName())){
                 node.setNodeValue("795796");
             }
         }

3 个答案:

答案 0 :(得分:1)

这样的事情:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
StreamResult result = new StreamResult(file);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);

答案 1 :(得分:0)

答案 2 :(得分:0)

此方法将DOM文档写入SD卡上的文件 如果要在模拟器中对此进行测试,请确保使用SD卡图像设置AVD图像(在图像创建期间完成)。

public static void writeXmlFile(Document doc, String filename) {
    try {
        // Prepare the DOM document for writing
        Source source = new DOMSource(doc);

        File file new File(Environment.getExternalStorageDirectory(),fileName);

        Result result = new StreamResult(file);

        // Write the DOM document to the file
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(source, result);
    } catch (TransformerConfigurationException e) {
         // handle exception
    } catch (TransformerException e) {
         // handle exception
    }
}