XML is commonly used in three ways of parsing:
DOM: All loaded into memory, generating a tree structure that occupies large memory.
SAJ: Event driven, fast, high efficiency, not support fallback.
Pull: Also use event-driven, simple syntax.
Steps:
1. Create an XML parser: xmlpullparser parser = Xml.newpullparser ();
2. Configure the parser: Parser.setinput (IS, "utf-8");//The input stream and encoding method for the XML file.
3. Parse according to the event.
int type = Parser.geteventtype ();//Get event Type = Parser.next ();//Get Next Event
Event Type:
Xmlpullparser.end_document the end of the document.
Xmlpullparser.start_tag start tag
Xmlpullparser.end_tag end Tag
Get tag name: Parser.getname ()
Get property: String idstr = parser.getattributevalue (0); The parameter is the property ID.
Get label contents: String temp = Parser.nexttext ();
code example:
Code structure:
Weathreservice.java
Package Com.serviatech.weather.service;import Java.io.inputstream;import Java.util.arraylist;import java.util.List ; import Org.xmlpull.v1.xmlpullparser;import Android.util.xml;import com.serviatech.weather.domain.WeatherInfo; public class WeatherService {public static list<weatherinfo> Getweatherinfos (InputStream is) throws Exception { List<weatherinfo> Weatherinfos = null; Weatherinfo weatherinfo = null; Xmlpullparser parser = Xml.newpullparser ();p arser.setinput (IS, "utf-8");//Initialize parser int type = Parser.geteventtype ();// Gets the event type while (type! = xmlpullparser.end_document) {switch (type) {case XmlPullParser.START_TAG:if ("Infos". Equals ( Parser.getname ())) {Weatherinfos = new arraylist<weatherinfo> ();} else if ("City". Equals (Parser.getname ())) { Weatherinfo = new Weatherinfo (); String idstr = parser.getattributevalue (0); Weatherinfo.setid (Integer.parseint (IDSTR));} else if ("temp". Equals (Parser.getname ())) {String temp = Parser.nexttext (); weatherinfo.settemp (temp);} else if ("wind". EQuals (Parser.getname ())) {String wind = Parser.nexttext (), Weatherinfo.setwind (wind);} else if ("name". Equals ( Parser.getname ())) {String name = Parser.nexttext (); Weatherinfo.setname (name);} Break;case XmlPullParser.END_TAG:if ("City". Equals (Parser.getname ())) {//a town has been disposed of Weatherinfos.add (Weatherinfo); Weatherinfo = null;//Convenient garbage collection machine back to}break;} Type = Parser.next ();} return Weatherinfos;}} /* * The parsing process defines a pointer to the beginning * tag tag, text * * Document START document END * * Starttag endtag * *
Weatherinfo.java
Package Com.serviatech.weather.domain;public class Weatherinfo {private int id;private string Name;private string temp; Private String wind;public int getId () {return ID;} @Overridepublic String toString () {return "Weatherinfos [city id=" + ID + ", First name =" + name + ", temperature =" + temp+ ", wind =" + Winds + " ]";} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String gettemp () {return temp;} public void Settemp (String temp) {this.temp = temp;} Public String Getwind () {return wind;} public void Setwind (String wind) {this.wind = Wind;}} /* * DOM is all loaded into memory. Generate a tree structure that consumes more memory * * SAX Event-based approach, fast, efficient, and cannot be rolled back. * Pull based on event parsing, syntax concise */
Mainactivity.java
Package Com.serviatech.weather;import Java.util.list;import Com.serviatech.weather.domain.weatherinfo;import Com.serviatech.weather.service.weatherservice;import Android.os.bundle;import Android.app.Activity;import Android.view.menu;import Android.widget.textview;import Android.widget.toast;public class MainActivity extends Activity {private TextView TV; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); TV = (TextView) Findviewbyid (r.id.tv); try {list< weatherinfo> infos = Weatherservice.getweatherinfos (MainActivity.this.getClassLoader (). getResourceAsStream (" Weather.xml ")); StringBuilder sb = new StringBuilder (); for (Weatherinfo Info:infos) {sb.append (info.tostring ()); Sb.append ("\ n");} Tv.settext (Sb.tostring ());} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace (); Toast.maketext (This, "Parse information failed", 0). Show ();}} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate theMenu This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}