简体   繁体   English

附加XML文件到android

[英]Writing XML file to android after appending it

I'm need to write the XML file in android and replace it with the new one. 我需要在android中编写XML文件,并将其替换为新文件。 The code is working properly but nothing changed in the XML file I have. 代码工作正常,但是我拥有的XML文件没有任何更改。

any ideas? 有任何想法吗?

try{

FileOutputStream fOut = openFileOutput("/data/data/test.fileshow/files/Landmarks.xml", MODE_WORLD_READABLE);

OutputStreamWriter osw = new OutputStreamWriter(fOut); 
String filepath = "Landmarks.xml";

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
     Document doc = docBuilder.parse(filepath);
     Element Row, Longitude, Latitude, Title, Category, Rating;

            Node staff = doc.getElementsByTagName("Root").item(0);

         Row=doc.createElement("Row");
         Longitude=doc.createElement("Longitude");
         Longitude.appendChild(doc.createTextNode("555"));
         Row.appendChild(Longitude);
         Latitude=doc.createElement("Latitude");
         Latitude.appendChild(doc.createTextNode("ABCCamera"));
         Row.appendChild(Latitude);
         Title=doc.createElement("Title");
         Title.appendChild(doc.createTextNode("title"));
         Row.appendChild(Title);
         Category=doc.createElement("Category");
         Category.appendChild(doc.createTextNode("category"));
         Row.appendChild(Category);
         Rating=doc.createElement("Rating");
         Rating.appendChild(doc.createTextNode("rating"));
         Row.appendChild(Rating);
         staff.appendChild(Row);


        //write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result =  new StreamResult(new File(filepath));
        transformer.transform(source, result);

        osw.flush();
        osw.close();

      }catch(ParserConfigurationException pce){
     pce.printStackTrace();
      }catch(TransformerException tfe){
     tfe.printStackTrace();
      }catch(IOException ioe){
     ioe.printStackTrace();
      }catch(SAXException sae){
     sae.printStackTrace();
      }

I was having issues writing DOM documents and this set me on the right path. 我在编写DOM文档时遇到问题,这使我走上了正确的道路。 From your code, I had to bind the OutputStreamWriter to the StreamResult. 从您的代码中,我必须将OutputStreamWriter绑定到StreamResult。

After you instantiate: 实例化之后:

StreamResult result =  new StreamResult(new File(filepath));

call the following: 拨打以下电话:

result.setWriter(osw);

before performing the transform. 在执行转换之前。 This worked for me. 这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM