簡體   English   中英

將修改后的xml保存到Android內部存儲中

[英]Save modified xml into internal storage Android

我在/data/data.my.package.app/files/file.xml中的現有xml文件中添加了節點,我只想保存該文件,但沒有找到。

我嘗試了在其他帖子中看到的此功能:

private void save(Document newDoc) throws Exception{
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StreamResult result = new StreamResult(new File(context.getFilesDir().getAbsolutePath() + "/file.xml"));
    Source source = new DOMSource(newDoc);
    transformer.transform(source, result);
}

但是我在tranformer.transform()上得到了一個空指針異常。這就是初始化文檔文件的方式。

FileInputStream is = new FileInputStream(context.getFilesDir().getAbsolutePath() + "/file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);

非常感謝AD的幫助

該文件不能是新文件。 必須已經存在:

StreamResult result = 
     new StreamResult(new File(context.getFilesDir().getAbsolutePath() +   "/file.xml"));

對我來說,這項工作:

//save the doc as string  in a text file with the same name (extension   .xml)
save(this, body, dir, FILENAME_XML);

//apply the transformer
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory_p.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(
    new File(dir+File.separator+FILENAME_XML));
transformer.transform(source, result);

生成文件xml。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM