Search code examples
androidxmltransformer-model

How can update my xml file in android?


Below code run without any error, but my xml file in assets folder does not change. why?

Is there a better way?.

              try {
                    InputStream is = getAssets().open("file.xml");



                    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                    Document doc = docBuilder.parse(is);

                    Node earth = doc.getFirstChild();
                    NamedNodeMap earthAttributes = earth.getAttributes();
                    Attr galaxy = doc.createAttribute("galaxy");
                    galaxy.setValue("milky way");
                    earthAttributes.setNamedItem(galaxy);

                    Node canada = doc.createElement("country");
                    canada.setTextContent("ca");
                    earth.appendChild(canada);

                    Transformer transformer = TransformerFactory.newInstance().newTransformer();
                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

                    //Initialize StreamResult with File object to save to file
                    StreamResult result = new StreamResult(new StringWriter());
                    DOMSource source = new DOMSource(doc);
                    transformer.transform(source, result);

                    String xmlString = result.getWriter().toString();
                    dialog.setMessage(xmlString);
                    dialog.show();

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ParserConfigurationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SAXException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (TransformerException e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                }

I use this permission in manifest file:

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

Solution

  • Your APK is read only. You cannot modify anything, incl. assets/ folder. If you need its content to be sort of modifiable template, you must copy it out of assets/ first.