There are three ways to parse XML in Android: SAX (Simple API XML), DOM (Document objrect Model), and the recommended pull parsing method for Android. The following is a detailed description of the three parsing methods one by one.
Suppose you want to parse a person.xml document
<?xml version= "1.0" encoding= "UTF-8"?>
<persons>
<person id= "1" >
<name>zhangsan</name>
<age>21</age>
</person>
<person id= "2" >
<name>lisi</name>
<age>22</age>
</person>
<person id= "3" >
<name>wangwu</name>
<age>222</age>
</person>
</persons>
First, we introduce sax parsing, sax is a standard interface for event-driven XML parsing and does not change how sax works simply by sequentially scanning the document, when the document is scanned to start and end, the element begins and ends, The event handler is notified when the document ends, and the event handler acts accordingly, and then continues the same scan until the end of the document. The following combination of code analysis
public class Saxpersonservice {
Public list<person> getpersons (InputStream instream) throws exception{
saxparserfactory factory = Saxparserfactory.newinstance ();//Create Sax parsing factory
saxparser paser = Factory.newsaxparser ();//Create SAX Parser
personpaser personpaser=new personpaser ();//Create event handler
paser.parse (instream, Personpaser);//Start parsing
instream.close ();//Close input stream
return personpaser.getpersons ();// Returns the parsed content
}
public final class Personpaser extends defaulthandler{//create event handlers, That is, the implementation class that writes ContentHandler, generally inherits from the DefaultHandler class
Public list<person> getpersons () {
return persons;
}
Private list<person> Persons=null;
Private String Tagname=null;
private person person=null;
{
//when a document start tag is encountered Create Person collection
public void Startdocument () throws saxexception persons=new arraylist<person> ();
}
//encountered an element node at the beginning of the processing method
public void Startelement (String uri, String localname, String qName,
attributes Attributes) throws Saxexception {
tagname = localname;
If a <person> tag is encountered, create a person
if ("Person". Equals (TagName)) {
person = new person ();
Person.setid (New Integer (Attributes.getvalue (0));//Remove the attribute within the tag
}
}
Actions when a text node is encountered
public void characters (char[] ch, int start, int length)
Throws Saxexception {
if (tagname!=null) {//text node must precede element node start tag
String data = new string (ch,start,length);//Remove the value of the text node
if ("Name". Equals (TagName)) {//if the preceding element node start tag is name
Person.setname (data);//assigns the value of the text node to the name of the person
}else if ("Age". Equals (TagName)) {//if the preceding element node start tag is age
Person.setage (data);//assigns the value of this node to the age of person
}
}
}
Operation encountered at end of element node
public void EndElement (string uri, String localname, String qName)
Throws Saxexception {
if ("Person". Equals (LocalName)) {//If </person> tag is encountered
Persons.add (person);//The person who created the completed person is added to the collection
person=null;//Empty Next person
}
tagname=null;//empty already tagged because the next node is being parsed
}
}
At this point, sax parsing is complete!
The following describes Dom parsing, the DOM, the object document model, which loads the entire XML document into memory (so inefficient, deprecated), each node as an object, combined with code analysis
public class Dompersonservice {
Public list<person> getpersons (InputStream instream) throws exception{
list<person> persons = new arraylist<person> ();
Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();//create Dom parsing factory
Documentbuilder dombuild = Factory.newdocumentbuilder ();//Create an Don Parser
Document DOM = Dombuild.parse (instream);//Start parsing XML documents and get an object model for the entire document
Element root= dom.getdocumentelement ();//Get root node <persons>
NodeList personlist = root.getelementsbytagname_r ("person");//Get all child nodes labeled <person> under the root node
for (int i = 0;i<personlist.getlength (); i++) {//Traverse person node
person person = new person ();//Create a person first
Element personelement = (Element) personlist.item (i);//get this second person element node
Person.setid (New Integer (Personelement.getattribute ("id")));//Get ID in the person node
NodeList personchilds = Personelement.getchildnodes ();//Get all child nodes under the person node
for (int j=0;j<personchilds.getlength ( ) (j + +) {//Traverse all child nodes under the person node
if (Personchilds.item (j). Getnodetype () = = Node.element_node) {//If it is an element node
element childelement = (Element) Personchilds.item (j); Get the element node
if ("Name". Equals (Childelement.getnodename ())) {// If the element node is the name node
person.setname (Childelement.getfirstchild (). Getnodevalue ());//Gets the value of the first text node under the name node
}else if ("Age". Equals ( Childelement.getnodename ())) {//If the element node is an age node, the
Person.setage (New Short (Childelement.getfirstchild (). Getnodevalue ()));//Gets the value of the first text byte point under the Age node
}
}
}
Persons.add (person);//The person element is added to the collection after iterating through all the child nodes under person
}
return persons;
}
At this point, the DOM parsing method ends!
The following describes pull parsing
Public class Pulpersonservice {
Public list<person> getpersons (InputStream instream) throws Exception {
List<Person> Persons = null;
person person = null;
xmlpullparser parser = Xml.newpullparser ();//Get Pull Parser
parser.setinput (instream, " UTF-8 ");//Set the encoding for the input stream
int EventType = Parser.geteventtype ();//Get the first event type
while ( EventType! = xmlpullparser.end_document) {//If the event type is not the end of the document, the event is constantly processed
switch (eventtype) {
case (xmlpullparser.start_document)://If it is a document start event
persons = new Arraylist<person> (); Create a person collection
break;
case ( Xmlpullparser.start_tag)://If you encounter a label start
string tagName = Parser.getname ();//Gets the name of the current element of the parser
if ("person". Equals ( TagName) {//If the current tag name is <person>
person = new Person ();//Create a person
person.setid (New Integer (Parser.getattributevalue (0)))//Assign the attribute value of the element to the ID
}
if (person! = NULL) {//If person has already created the complete
if ("Name". Equals (TagName))//If the current node tag is name
person.setname (The new String ( Parser.nexttext ()));
else if ("Age". Equals (TagName))//If the current element node tag is age
person.setage (New Short (Parser.nexttext ()));
}
break;
case (Xmlpullparser.end_tag)://If you encounter a label end
if ("Person". Equals (Parser.getname ())) {//If the person tag ends
Persons.add (person);//create completed person to join the collection
person = null;//and empty
}
Break
}
Eventtype=parser.next ();//Enter the next event handler
}
return persons;
}
at this point, three kinds of analytic methods have been elaborated!
Three ways to parse XML in Android