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:
Solution 1:
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:
DocumentBuilderFactoryfactory= DocumentBuilderFactory.newInstance();
DocumentBuilderbuilder= factory.newDocumentBuilder();
Documentdoc= builder.parse(context.openFileInput("MyFileName.xml")); // In My Case it's in the internal Storage
then make a NodeList
for all "car" elements by :
NodeListnodeslist= 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(inti=0 ; i < nodeslist.getLength() ; i ++){
Nodenode= nodeslist.item(i);
NamedNodeMapatt= node.getAttributes();
inth=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 :
TransformerFactorytransformerFactory= TransformerFactory.newInstance();
Transformertransformer= transformerFactory.newTransformer();
DOMSourcedSource=newDOMSource(doc);
StreamResultresult=newStreamResult(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 .
Post a Comment for "Update\modify An Xml File In Android"