【问题标题】:How to save & update the values in xml file?如何保存和更新 xml 文件中的值?
【发布时间】:2011-09-30 04:36:04
【问题描述】:

我正在从 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");
             }
         }

【问题讨论】:

    标签: android saxparser


    【解决方案1】:

    类似这样的:

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

    【讨论】:

      【解决方案2】:

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

      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
          }
      }
      

      【讨论】:

        【解决方案3】:
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-12
        • 2012-05-27
        • 2019-06-27
        • 2011-06-01
        相关资源
        最近更新 更多