androidxmlupdatexml

Update xml node in assets


I have an android application which I am trying to change a node value.

Below I can take xml file from assets folder and get the specific node I want.

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());

But when it comes to transform I stuck.

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);

Solution

  • You can't write/update files in assets folder. You need to copy the xml file from assets to sdcard and then modify it.

    Copy xml to sdcard:

    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());
        }
    

    Permission in manifest:

     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />