How to save and update values ​​in an XML file?

I am reading an xml file from an SD card. Here I want to change the values ​​of the XML file, and I want to save the file on the SD card.

My code is similar to below ... Please let me know how to save the XML file to the SD card after updating the values.

public void modifyNodeval(){ try{ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File("/sdcard/sss.xml")); //Get the staff element by tag name directly Node nodes = doc.getElementsByTagName("Employee").item(0); //loop the staff child node NodeList list = nodes.getChildNodes(); for (int i =0; i<list.getLength();i++){ Node node = list.item(i); //get the salary element, and update the value if("Emp_Name".equals(node.getNodeName())){ node.setNodeValue("795796"); } } 
+6
source share
3 answers

Something like that:

 Transformer transformer = TransformerFactory.newInstance().newTransformer(); StreamResult result = new StreamResult(file); DOMSource source = new DOMSource(doc); transformer.transform(source, result); 
+1
source

This method writes the DOM document to a file on the SD card. If you want to test this in the emulator, make sure your AVD image is set using the SD card image (taken during image creation).

 public static void writeXmlFile(Document doc, String filename) { try { // Prepare the DOM document for writing Source source = new DOMSource(doc); File file new File(Environment.getExternalStorageDirectory(),fileName); Result result = new StreamResult(file); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); } catch (TransformerConfigurationException e) { // handle exception } catch (TransformerException e) { // handle exception } } 
0
source

Source: https://habr.com/ru/post/892201/


All Articles