How to add tags to xml in android? and how to save this xml file?

I would like to add a new tag with some attributes with these values ​​to an xml file and save this XML file through the application. I wrote a method to add a new tag as a child in the xml file, which is available in the sdcard of the android emulator.The next method is to add a new tag as follows

public void appendTag(){ try{ DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse (new File("/sdcard/sample.xml")); Node node = doc.getElementsByTagName("earth").item(0); //append a new node to earth Element newelmnt = doc.createElement("new"); newelmnt.appendChild(doc.createTextNode("this is a text")); node.appendChild(newelmnt); } catch (Exception e) { e.printStackTrace(); } } 

after executing this method, I cannot find the new tag in the XML file.

may any help on how to add a new tag as a child in an xml file and how to save the changes?

If I use TransformerFactory, I get an error like ERROR / AndroidRuntime (13479): java.lang.VerifyError: com.sample.xmlapp.DOMClass I used the following

  TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("/sdcard/sample.xml")); transformer.transform(source, result); 
+7
source share
1 answer

Your in-memory document will be modified, but you will need to write it back to the file again.

Try adding this to write the document to the file again:

 TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("/sdcard/sample.xml")); transformer.transform(source, result); 
+2
source

All Articles