- DOM Parser.
- Pull Parser.
- SAX Parser.
<?xml version="1.0"?>which we need to parse to create an object from Person class:
<person>
<firstname>Jack</firstname>
<lastname>smith</lastname>
<age>28</age>
</person>
public class Person{Parsing the response with DOM Parser:
public String firstName;
public String lastName;
public int age;
}
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{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.
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));
}
0 comments:
Post a Comment