Wednesday, December 23, 2009

Parsing XML and storing elements in Database in Android

For one of my project I parsed XML file and stored each element in database according to ID. First of all, about parsing, there are three different types of parsing are there in Android as,

-DOM (Document Object Model)
-SAX (Simple API for XML)

A DOM parser works by parsing an XML file into a native data structure matching the hierarchy of the XML file. Most of the processing is done up front and the entire file is looked at, so a DOM parser typically uses the most memory of the three parsers.

A Pull Parser works by creating a loop that continually requests the next event and can then handle that event directly within the loop. The idea with the Pull Parser is that it can easily be stopped at any point, only do processing on demand, and remove the overhead of extra method calls and classes.

SAX parser is an event driven parser. Events are fired, when XML features such as XML text nodes, XML element node etc. are encountered. SAX parsing is uni directional, previously parsed data cannot be re-read without starting the parsing operation again. A SAX parser works by having the user implement a class with method handlers for various events.

DOM Parser in Android

Syntax for DOM Parsing is,

InputStream is = context.getResources().openRawResource(R.raw.xmlfile);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);

This is the basic syntax for DOM parsing, then according to our requirement, we can take the node, node values, attribute values etc.

NodeList scrNodes = doc.getElementsByTagName("note");
If the node have any attributes, then , we can get it using
NamedNodeMap nnm = scrNodes.item(0).getAttributes();
To get the value of the node,
String value = scrNodes.item(0).getNodeValue();

Pull Parser in Android

XML Pullparser we can directly get through,

XmlPullParser xpp = ctx.getResource().getXml(R.xml.sample);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
if (eventType == XmlPullParser.START_TAG)
// parse stuff
else if (eventType == XmlPullParser.END_TAG)
// parse stuff
eventType =;

SAX Parser in Android

Syntax for SAX parser is,

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
SaxHandler saxHandler = new SaxHandler();

public class SaxHandler extends DefaultHandler{

Storing XML elements in Database

For storing in database, first open the database and I used proper sql statement through execSQL() for storing elements in database.

The code is,

SQLiteDatabase datbase = ctContext.openOrCreateDatabase("MyDatabase", Context.MODE_PRIVATE, null);
database.execSQL("CREATE TABLE IF NOT EXISTS MyTable (id int(3), value varchar)");
database.execSQL("INSERT INTO MyTable (1, "")");

No comments:

Post a Comment