Android Access Weather Service 01--build Xmlpullparser

Source: Internet
Author: User

Pull Mode parsing principle:

Similar to the SAX parser simulation, it also provides the same event-driven. Use Parser.next () to enter the next element and trigger the corresponding event. Events are sent as numeric codes, so you can use a switch to handle the events of interest. When the element begins parsing, the Parser.nexttext () method is called to get the value of the next text type element.

Pull mode parsing steps:

1. Get a Xmlpullparser object here are two ways to get Xmlpullparser objects:

1) Through XML this tool class of. Newpullparser () way to get   2) created by Xmlpullparserfactory Factory

Get Xmlpullparserfacotry Factory
[Java] View plaincopyprint?

Xmlpullparserfactory factory = Xmlpullparserfactory.newinstance ();  Xmlpullparser Xmlparser = Factory.newpullparser ();

2, then set the input stream and encoding format according to the Xmlpullparser object
[Java] View plaincopyprint?

Parser.setinput (InputStream, "UTF-8");

3. Then loop through all the nodes to determine which node to read into by the code at the beginning of the document

The values for Xmlparser.geteventtype () are:

Start_document: Document Start

End_document: Document End

Start_tag: Start reading tags

End_tag: End of label

Text: What is read is the textual content

A simple example:
[Java] View plaincopyprint?

Import java.io.IOException;  Import Java.io.StringReader;  Import Org.xmlpull.v1.XmlPullParser;  Import org.xmlpull.v1.XmlPullParserException;  Import Org.xmlpull.v1.XmlPullParserFactory;          public class simplexmlpullapp{public static void Main (String args[]) throws Xmlpullparserexception, ioexception{         Xmlpullparserfactory factory = Xmlpullparserfactory.newinstance ();          Factory.setnamespaceaware (TRUE);           Xmlpullparser xpp = Factory.newpullparser ();          Xpp.setinput (New StringReader ("<foo>hello world!</foo>"));          int eventtype = Xpp.geteventtype ();               while (eventtype! = xmlpullparser.end_document) {if (EventType = = xmlpullparser.start_document) {           SYSTEM.OUT.PRINTLN ("Start document");           } else if (EventType = = Xmlpullparser.start_tag) {System.out.println ("START TAG" +xpp.getname ()); } else if (EventType = = Xmlpullparser.end_tag) {System.out.println ("ENDTag "+xpp.getname ());           } else if (EventType = = Xmlpullparser.text) {System.out.println ("TEXT" +xpp.gettext ());          } EventType = Xpp.next ();      } System.out.println ("End document"); }  }

Output Result:

Start Document

Start tag Foo

Text Hello world!

End tag Foo

Or an example of the above section: reading the contents of an XML file constructs the content as a person object and then reads the contents of the XML document to add its person object to a list collection

Person.xml:
[HTML] View Plaincopyprint?

<?xml version= "1.0" encoding= "UTF-8"?>  <persons>         <person id= "All" >                <name> li Ming </name>                <age>30</age>         </person>         <person id= >                <name> Li Xiangmei </name>                <age>25</age>         </person>  </persons>

Person class:
[Java] View plaincopyprint?

public class Person {      private Integer ID;      private String name;      private short age;          Public Integer getId () {         return ID;      }      public void SetId (Integer id) {         this.id = ID;      }       Public String GetName () {         return name;      }      public void SetName (String name) {         this.name = name;      }       public short getage () {         return age;      }      public void Setage {         this.age = age;      }       @Override public      String toString () {         return ' person [age= ' + Age + ', id= "+ ID +", name= "+ name +"] ";      }  }

Business Bean
[Java] View plaincopyprint?

public static list<person> readXml (InputStream inputstream) throws Exception {list<person> PE       Rsons=null;       Xmlpullparser Object Xmlpullparser parser = Xml.newpullparser ();       Set the input stream and encode parser.setinput (InputStream, "UTF-8");       File start code int eventcode = Parser.geteventtype ();       person person = null; while (EventCode! = xmlpullparser.end_document) {switch (EventCode) {//document start case Xmlpullpa Rser.              Start_document://Initialize persons = new arraylist<person> ();           Break Case Xmlpullparser.start_tag://start tag if (' Person '. Equals (Parser.getname ())) {person = new Pe                 Rson ();              Person.setid (Integer.parseint (parser.getattributevalue (0))); } else if (person!=null) {if ("name". Equals (Parser.getname ())) {//nextne XT () If the content of the next element is text, it is appropriate to use PErson.setname (Parser.nexttext ()); } else if ("Age". Equals (Parser.getname ())) {Person.setage (New short (Parser.nexttext ())                  );           }} break;                  Case xmlpullparser.end_tag://end Tag if ("Person". Equals (Parser.getname ()) && person!=null) {                  Persons.add (person);                person=null;//to throw again null} break;       }//Next node EventCode = Parser.next ();    } return persons; }

Test:
[Java] View plaincopyprint?

public class Saxpersonservicetest extends Androidtestcase {       private static final String TAG = "Logtest";  Pull mode public      void Testpullreadxml () throws Exception {          System.out.println ("Testpullreadxml");         InputStream InputStream = SAXPersonServiceTest.class.getClassLoader ()                . getResourceAsStream ("person.xml");         list<person> list = Pullpersonservice.readxml (InputStream);          System.out.println (List.size ());         for (person person:list) {             System.out.println (person);}}}  

Android Access Weather Service 01--build Xmlpullparser

Related Article

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.