Pages
Parsing XML wit DOM parser
7:05 PM
Posted by Mina Samy
- DOM Parser.
- Pull Parser.
- SAX Parser.
<?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: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.
| Reactions: |
This entry was posted on October 4, 2009 at 12:14 pm, and is filed under
DOM Parser,
Parsing,
XML
. Follow any responses to this post through RSS. You can leave a response, or trackback from your own site.
Subscribe to:
Post Comments (Atom)









November 11, 2011 11:55 PM
xml is a very interesting language to be used and contain the data object model or abbreviated DOM.tutorial very good and hopefully can help me in building a web application thanks
January 10, 2012 11:58 AM
what does the "response" refer to here??
January 22, 2012 9:21 AM
what does response refer to here???
January 22, 2012 11:13 AM