Three ways to parse XML in Android

Source: Internet
Author: User
Tags tag name
<span id="Label3"></p><p><p><span>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.</span></p></p><p><p><span>Suppose you want to parse a person.xml document</span></p></p><p align="left"><p align="left"><?xml version= "1.0" encoding= "UTF-8"?><br><persons><br><person id= "1" ><br><name>zhangsan</name><br><age>21</age><br></person><br><person id= "2" ><br><name>lisi</name><br><age>22</age><br></person><br><person id= "3" ><br><name>wangwu</name><br><age>222</age><br></person><br></persons></p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left"></p></p><p><p>first, sax <span style="color: #ed1c24;"> <span style="font-size: large;">Parsing is introduced, and</span><span style="font-size: medium;">sax is a standard interface for Event-driven XML parsing that does not change how sax works simply by sequentially scanning a document when the document is scanned to start and end, The event handler is notified when the element starts and ends, where 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</span></span></p></p><p><p><strong><span>public class Saxpersonservice {</span></strong></p></p><p><p><span><strong>Public list<person> getpersons (inputstream Instream) throws exception{<br>SAXParserFactory factory = saxparserfactory.newinstance ();//create sax parsing factory<br>SAXParser paser = factory.newsaxparser ();//create sax Parser<br>Personpaser personpaser=new Personpaser ();//create event handler<br>Paser.parse (instream,personpaser);//start Parsing<br>Instream.close ();//close Input Stream<br>Return personpaser.getpersons ();//returns the parsed content<br><br>}<br>Public final class Personpaser extends Defaulthandler{//creates an event handler,</strong> which is the implementation class that writes the contenthandler, and generally inherits from the DefaultHandler class</span></p></p><p><p><span><strong>Public list<person> getpersons () {<br>Return persons;<br>}</strong><br><strong>Private List<person> persons=null;<br>Private String tagname=null;<br>Private person person=null;</strong></span></p></p><p><p><span><strong>{</strong></span></p></p><p><p><span><strong>Create a person collection when a document start tag is encountered<br>public void Startdocument () throws saxexception persons=new arraylist<person> ();<br>}<br>How to handle element nodes at the beginning of the encounter<br>public void startelement (string uri, string localname, string qName,<br>Attributes Attributes) throws Saxexception {<br>TagName = localname;</strong></span></p></p><p><p><span><strong>If a <person> tag is encountered, create a person<br>If ("person". equals (tagName)) {<br>person = new Person ();<br>Person.setid (new Integer (attributes.getvalue (0));//remove the attribute within the tag<br>}</strong></span></p></p><p><p><span><strong>}</strong></span></p></p><p><p><span><strong>Actions when a text node is encountered</strong></span></p></p><p><p><span><strong>public void characters (char[] ch, int start, int Length)<br>Throws Saxexception {<br>If (tagname!=null) {//text node must precede element node start tag<br>String data = new String (ch,start,length);//remove The value of the text node<br>If ("name". equals (tagName)) {//if The preceding element node start tag is name<br>Person.setname (data);//assigns The value of the text node to the name of the person<br>}else if ("age". equals (tagName)) {//if The preceding element node start tag is age<br>Person.setage (data);//assigns The value of this node to the age of person<br>}<br>}</strong></span></p></p><p><p><span><strong>}</strong></span></p></p><p><p><span><strong>Operation encountered at end of element node<br>public void EndElement (string uri, string localname, string QName)<br>Throws Saxexception {<br>If ("person". equals (localname)) {//if </person> tag is encountered<br>Persons.add (person);//the person who created the completed person is added to the collection<br>Person=null;//empty Next person<br>}<br>Tagname=null;//empty already tagged because the next node is being parsed<br>}<br>}</strong></span></p></p><p><p><span style="font-size: medium;">At this point, sax parsing is complete!</span></p></p><p><p></p></p><p><p></p></p><p><p><span style="color: #ed1c24; font-size: medium;">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</span></p></p><p><p><span><strong>public class Dompersonservice {</strong></span></p></p><p><span><span> <strong>  public list<person> getpersons (inputstream Instream) throws exception{<br>    list<person> persons = new Arraylist<person> (); <br>   documentbuilderfactory factory = documentbuilderfactory.newinstance ();//create Dom parsing factory <br>    Documentbuilder Dombuild = Factory.newdocumentbuilder ();//create The Don parser <br>   document dom = Dombuild.parse ( Instream);//start parsing the XML document and get the entire Document Object Model <br>   element root= dom.getdocumentelement ();//get root node <persons> <br>   nodelist personlist = root.getelementsbytagname_r ("person");//get All child nodes labeled <person> under the root node <br>   for (int i = 0;i<personlist.getlength (); i++) {//traverse person node <br>     person person = New person ();//first Create a person <br>     element personelement = (Element) Personlist.item (i);// Get this time person element node <br>     person.setid (new Integer (personelement.getattribute ("id")));// Get ID </strong> </span> in the person node</span><span><span><strong><br>NodeList Personchilds = personelement.getchildnodes ();//get All child nodes under the person node<br>For (int J=0;j<personchilds.getlength (); j + +) {//traverse all child nodes under the person node<br>If (personchilds.item (j). getnodetype () ==node.element_node) {//if It is an element node<br>Element childelement = (element) Personchilds.item (j); Get the element node<br>If ("name". equals (childelement.getnodename ())) {//if The element node is a name node<br>Person.setname (childelement.getfirstchild (). Getnodevalue ());//get The value of the first text book node under the name node<br>}else if ("age". equals (childelement.getnodename ())) {//if The element node is an age node,</strong> </span></span><span><span><strong><br>Person.setage (new Short (childelement.getfirstchild (). getnodevalue ()));//gets The value of the first text byte point under the Age node</strong> </span></span><span><span><strong><br>}<br>}<br>}<br>Persons.add (person);//the person element is added to the collection after iterating through all the child nodes under person<br>}<br>Return persons;<br>}</strong></span></span></p><p><p></p></p><p><p></p></p><p><p>At this point, the DOM parsing method ends!</p></p><p><p></p></p><p><p></p></p><p><p>the <span style="color: #ed1c24;">following describes pull parsing</span></p></p><p><p>public <strong> <span>class Pulpersonservice {</span></strong></p></p><p><p> <strong> <span>  public list<person> getpersons (inputstream Instream) throws Exception {<br>    list<person> Persons = null; <br>   person person = null; <br>   xmlpullparser parser = Xml.newpullparser ();//get Pull parser <br>   parser.setinput (instream, " UTF-8 ");//set the encoding for the input stream <br>   int EventType = Parser.geteventtype ();//get The first event type <br>   while ( eventtype! = Xmlpullparser.end_document) {//if The event type is not the end of the document, the event is constantly processed <br>    switch (eventtype) {<br>    case (xmlpullparser.start_document)://if It is a document start event <br>     persons = new Arraylist<person> (); Create a person collection <br>     break; <br>    case (xmlpullparser.start_tag)://if you encounter a label start </span> </strong> </p></p><p><p> <strong> <span>     string tagName = parser.getname ();//gets The name of the current element of the parser <br>      if ("person". equals (tagName)) {//if The current tag name is <person> <br>      person = new person ();//create a person <br>      person.setid (new Integer (parser.getattributevalue (0)));// Assigns the attribute value of the element to the ID <br>     } <br>     if (person! = Null) {//if The person has created the complete <br>      if ("name". equals (tagName))//if The current node tag is name <br>        person.setname (new String (parser.nexttext ())); <br>      else if ("age". equals (tagName))//if the current element node tag is age <br>        person.setage (new Short (parser.nexttext ())); <br>     } <br>    break; <br>    case (xmlpullparser.end_tag)://if you encounter a label end </span> </strong> </p></p><p><p><strong><span>If ("person". equals (parser.getname ())) {//if the person tag ends<br>Persons.add (person);//create completed person to join the collection<br>person = Null;//and Empty<br>}<br>Break<br>}<br>Eventtype=parser.next ();//enter the next event handler<br>}<br>Return persons;<br>}</span></strong></p></p><p><p><span></span></p></p><p><p><span>At this point, three kinds of analytic methods have been elaborated!</span></p></p><p><p></p></p><p><p></p></p><p><p><span>Reproduced In: http://blog.sina.com.cn/s/blog_5a48dd2d0100sdo9.html</span></p></p><p><p>Three ways to parse XML in Android</p></p></span>

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.