Three ways to parse XML in Android

Source: Internet
Author: User
Tags gettext tagname


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.

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>

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.

    public class Saxpersonservice {public list<person> getpersons (InputStream instream) throws exception{ SAXParserFactory factory = Saxparserfactory.newinstance ();//Create Sax parsing factory SAXParser Paser = Factory.newsaxparser ();//Create SA X parser Personpaser Personpaser=new personpaser ()//Create event handler Paser.parse (Instream,personpaser);//Start parsing instream . Close ();//Close input stream return personpaser.getpersons ();//return parsed content} public final class Personpaser extends Defaulthan dler{//creates an event handler, which is the implementation class that writes ContentHandler, generally inherits from DefaultHandler class public list<person> getpersons () {return persons    ;      } private list<person> Persons=null;      Private String Tagname=null;    private person person=null; {//When the document start tag is encountered create a person collection public void startdocument () throws Saxexception persons=new arraylist<      Person> (); }//encountered element node at the beginning of the processing method public void Startelement (string uri, String localname, String qName, Attributes Attri Butes) 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)))///Take the attribute inside the tag}}//operation public void characters when encountering text node (ch ar[] ch, int start, int length) throws Saxexception {if (tagname!=null) {///text node must precede element node start tag String da Ta = 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), or the value of the text node is assigned to the person's name}else if ("Age". Equals (TagName)) {//if the preceding element node start tag is the Age Person.setage (the new short (d ATA)) or//The value of this node is assigned to the person's age}}}//encountered an element node at the end of the Operation public void EndElement (string uri, String loc Alname, String qName) throws Saxexception {if ("person". Equals (LocalName)) {//If you encounter </person> mark per Sons.add (person);//creates the completed person into the collection to person=null;//empty the next person} tagname=null;//empty already tagged because the next node is to be resolved}} 
DOM, the object document model, is to load 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<per  son> persons = new arraylist<person> (); Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();//Create DOM Resolution factory Documentbuilder Dombuild = Factory.newdocumentbuilder ();//Create an Don parser document DOM = Dombuild.parse (instream);//Start parsing the XML document and get the entire Document Object model Element Root= dom.getdocumentelement ();//Get root node <persons> NodeList personlist = root.getelementsbytagname_r ("person"); /Get all child nodes under the root node labeled <person> for (int i = 0;i<personlist.getlength (); i++) {//Traverse person node person person = new person ( );//first create a person element personelement = (Element) personlist.item (i);//Get this time person elements node Person.setid (the new Integer (pers Onelement.getattribute ("id")));//Get ID in 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). Getn Odetype () ==node.Element_node) {//If it is an element node, element childelement = (Element) Personchilds.item (j);//Gets the element node if ("Name". Equals (c Hildelement.getnodename ())) {//If the element node is the name node Person.setname (Childelement.getfirstchild (). Getnodevalue ());// Get 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, person.setage (New Sh ORT (Childelement.getfirstchild (). Getnodevalue ()));//Get the value of the first text byte point under the Age node}}} persons.add (person);//End of PE Add the person element to the collection after all child nodes under Rson} return persons;}
Pull parsing:
public class Pulpersonservice {public list<person> getpersons (InputStream instream) throws Exception {List<per  son> persons = NULL;  person person = null; Xmlpullparser parser = Xml.newpullparser ();//Get Pull Parser parser.setinput (instream, "UTF-8");//set encoding int eventtype = p for the input stream Arser.geteventtype ();//Gets the first event type while (eventtype! = xmlpullparser.end_document) {//If the event type is not the end of the document, the event switch is processed continuously (    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 ();//Get the name of the current element of the parser if ("person". Equals (Tagn AME) {//If the current tag name is <person> person = new person ();//Create a person Person.setid (the new Integer (Parser.getattributeva      Lue (0)));//Assign the attribute value of the element to the ID} if (person! = NULL) {//If the person has already created complete if ("Name". Equals (TagName))//If the current node tag is name     Person.setname (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 the end of the label if ("Person". Equals (Parser.getname ())) {//If the person tag ends Persons.add (person)   ;//will create the completed person into the collection person = null;//and Empty} break; } eventtype=parser.next ();//Enter next event processing} return persons;}

The second type:

 Public list<beauty> Parse (InputStream is) throws Exception {list<beauty> mlist = null;      Beauty Beauty = null;      Create a Xmlpullparser instance from android.util.Xml xmlpullparser xpp = Xml.newpullparser ();      Sets the input stream and indicates the encoding method Xpp.setinput (IS, "UTF-8");      produces the first event int eventtype = Xpp.geteventtype ();                       while (eventtype! = xmlpullparser.end_document) {switch (EventType) {//Determines whether the current event is a document start event Case XmlPullParser.START_DOCUMENT:mList = new arraylist<beauty> ();                       Initializes the books set to break; Determines whether the current event is a LABEL element start event Case XmlPullParser.START_TAG:if (Xpp.getname (). Equal                           S ("Beauty")) {//Determine if the start tag element is book beauty = new Beauty ();  } else if (Xpp.getname () equals ("name")) {EventType = Xpp.next ();//Let the parser point to the value of the Name property                             Get the property value of the name tag and set beauty name Beauty.setname (Xpp.gettext ()); } else if (Xpp.getname () Equals ("Age")) {//To determine whether the start tag element is a book event                               Type = Xpp.next ();//Let the parser point to the value of the Age property//Get the attribute value of the age tag and set the Age of beauty                           Beauty.setage (Xpp.gettext ());                       } break; Determines whether the current event is a LABEL element end Event Case XmlPullParser.END_TAG:if (Xpp.getname (). Equals (                               "Beauty") {//Determine if the end tag element is book Mlist.add (Beauty);//Add book to books collection                           Beauty = null;                       } break;                   }//Enter the next element and trigger the corresponding event EventType = Xpp.next ();      } return mlist;   }

Three ways to parse XML in Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.