How to save & update the values in xml file?
Asked Answered
W

3

7

I am reading a xml file from the SD card. Here I want to change the values of the XML file and I want to save the file to the sd card..

My code is like below.... Please guide me how to save 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");
             }
         }
Wineskin answered 7/7, 2011 at 6:3 Comment(0)
C
2

Something like this:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
StreamResult result = new StreamResult(file);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
Caterer answered 7/7, 2011 at 6:9 Comment(0)
F
1

how to modify xml node value?

Fein answered 7/7, 2011 at 6:5 Comment(0)
D
1

This method writes a DOM document to a file on the SD Card If you want to test this in the emulator, make sure your AVD image is setup with an SD Card image (done 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
    }
}
Deportation answered 7/7, 2011 at 6:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.