Saturday, July 2, 2011

Parsing XML wit DOM parser

Android offers three types of XML parsers:
  1. DOM Parser.
  2. Pull Parser.
  3. SAX Parser.
we'll demonstrate each using the following xml example:
<?xml version="1.0"?>
<person>
<firstname>Jack</firstname>
<lastname>smith</lastname>
<age>28</age>
</person>
which we need to parse to create an object from Person class:
public class Person{
public String firstName;
public String lastName;
public int age;
}
Parsing the response with DOM Parser:
Android provides org.w3c.dom library that contains classes used to parse xml by constructing a document and
matching each node to parse the info.
to parse our example response with DOM parser, we implement a function like this
void parseByDOM(String response) throws ParserConfigurationException, SAXException, IOException{
Person person=new Person();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(response)));
// normalize the document
doc.getDocumentElement().normalize();
// get the root node
NodeList nodeList = doc.getElementsByTagName("person");
Node node=nodeList.item(0);
// the  node has three child nodes
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
Node temp=node.getChildNodes().item(i);
if(temp.getNodeName().equalsIgnoreCase("firstname")){
person.firstName=temp.getTextContent();
}
else if(temp.getNodeName().equalsIgnoreCase("lastname")){
person.lastName=temp.getTextContent();
}
else if(temp.getNodeName().equalsIgnoreCase("age")){
person.age=Integer.parseInt(temp.getTextContent());
}

}

Log.e("person", person.firstName+ " "+person.lastName+" "+String.valueOf(person.age));
}
The previous method is good, it retrieves the info correctly, but it requires that you are familiar with the xml structure so that you know the order of each xml node.

No comments:

Post a Comment