我有一个Android应用程序,我正在尝试更改节点值。
下面我可以从assets文件夹中获取xml文件并获取我想要的特定节点。
InputStream in_s = getApplicationContext().getAssets().open("platform.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = (Document) docBuilder.parse(in_s);
Node path = doc.getElementsByTagName("path").item(0);
path.setNodeValue(txtPath.getText().toString());
但是当涉及变换时,我卡住了。
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer trans = transFactory.newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult("platform.xml");
//there should be something to write to xml file in assets.. I just cant figure it out..
trans.transform(source, result);
答案 0 :(得分:0)
您无法在assets文件夹中编写/更新文件。您需要将xml文件从assets复制到sdcard,然后进行修改。
将xml复制到SD卡:
String destFile = Environment.getExternalStorageDirectory().toString();
try {
File f2 = new File(destFile);
InputStream in = getAssets().open("file.xml");
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out
.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch (IOException e) {
System.out.println(e.getMessage());
}
清单中的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
答案 1 :(得分:0)
Android资源都是只读的。您无法动态更改或修改它。您只能读取资源,既不能更新资源也不能写入资源。