How to append an XML file in Android?
I'm writing an XML file to the sd card, and开发者_如何学运维 I need to be able to open that XML file and append data to it. How can I accomplish this? For example, my XML file is:
<items>
<item attr="value">data</item>
<item attr="value2">data 2</item>
</items>
I later need to open this XML file and append a new item to it:
<item attr="value3">data 3</item>
How can I do this?
You can use a sax parser that reads the file, outputs all elements by default and when it finds the closing {}, first insert the new item, then the closing tag.
Sax parsers are available by default in Android.
One example on how to deal with Sax at all can be found here.
What you want is to obtain a Document class version of your XML file. You can do this using a DOM Parser. From the Document class you can then manipulate it and write it back out with your modifications.
Here's code on DOM parsing.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(myfilepath);
More information on different approaches to XML in Android can be found here.
精彩评论