Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update\Modify an XML file in Android

I want to know how I can update an XML file in real time. I had this file for example:

<?xml version="1.0" encoding="UTF-8"?>
    <Cars>
        <car make="Toyota" model="95" hp="78" price="120"/>
        <car make="kia" model="03" hp="80" price="300"/>
    </Cars>

What should I do to update the price value like this one? :

<?xml version="1.0" encoding="UTF-8"?>
    <Cars>
        <car make="Toyota" model="95" hp="78" price="50"/>
        <car make="kia" model="03" hp="80" price="100"/>
    </Cars>

I have searched the web but all I found was how to parse, and how to write the whole file using XmlSerializer, but not how to modify. Also I have found this in Java but I failed to implement it on Android because I'm very new to the android-xml world.

like image 890
Khalil Tam Avatar asked Dec 19 '22 18:12

Khalil Tam


1 Answers

OK after long day with search and tries I have reached my Goal using Java's DOM . To modify an XML file first instantiate these to handle the XML:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(context.openFileInput("MyFileName.xml")); // In My Case it's in the internal Storage

then make a NodeList for all "car" elements by :

NodeList nodeslist = doc.getElementsByTagName("car");

or all elements by replacing the car String with "*".

Now it well search in every node attributes till it fine the "price" value of KIA for example:

for(int i = 0 ; i < nodeslist.getLength() ; i ++){
            Node node = nodeslist.item(i);
            NamedNodeMap att = node.getAttributes();
            int h = 0;
            boolean isKIA= false;
            while( h < att.getLength()) {
                Node car= att.item(h);
                if(car.getNodeValue().equals("kia"))
                   isKIA= true;      
                if(h == 3 && setSpeed)   // When h=3 because the price is the third attribute
                   playerName.setNodeValue("100");   
                 h += 1;  // To get The Next Attribute.
           }
}

OK Finally , Save the new File In the same location using Transformer like this :

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource dSource = new DOMSource(doc);
StreamResult result = new StreamResult(context.openFileOutput("MyFileName.xml", Context.MODE_PRIVATE));  // To save it in the Internal Storage
transformer.transform(dSource, result);

That's it :) . I hope this will helps .

like image 132
Khalil Tam Avatar answered Dec 21 '22 11:12

Khalil Tam