Android uses the pull method to parse xml files, androidpull
Android parses XML ----------------------------- the basics are rock-solid.
On the android platform, you can use SAX, DOM, And the built-in Pull parser to parse xml files. This article mainly introduces the use of pull to parse xml files. The Running Method of the pull parser is similar to that of the SAX Parser. It also has the starting element and ending element event, and can be parsed cyclically. You can use nextText () to obtain the value of a Text element.
The XML file to be parsed is stored in the assets Directory.
<? Xml version = "1.0" encoding = "UTF-8"?> <Info city = '3'> <name> Shenzhen </name> <temp> 28 ℃ </temp> <weather> cloudy </weather> <msg> suitable weather, wear a bikini! </Msg> </info>
Create a javabean to store parsed data and create a WeatherInfo class, as shown below:
public class WeatherInfo { private String name; private String temp; private String weather; private String msg; 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 getWeather() { return weather; } public void setWeather(String weather) { this.weather = weather; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public String toString() { return "[name=" + name + ", temp=" + temp + ", weather=" + weather + ", msg=" + msg + "]"; } }
Start parsing below
// Context, save the current application, system resources, and configure etc AssetManager am = this. getAssets (); try {InputStream is = am. open ("weather. xml "); // 1, create xml parser XmlPullParser parser = Xml. newPullParser (); // 2. initialize the parser, set the stream data to be parsed, and set the encoding method parser. setInput (is, "UTF-8"); // 3, loop parsing int type = parser. getEventType (); WeatherInfo info = new WeatherInfo (); while (type! = XmlPullParser. END_DOCUMENT) {// if it is the start label if (type = XmlPullParser. START_TAG) {if ("name ". equals (parser. getName () {String name = parser. nextText (); // get text data info. setName (name);} else if ("temp ". equals (parser. getName () {info. setTemp (parser. nextText ();} else if ("weather ". equals (parser. getName () {info. setWeather (parser. nextText ();} else if ("msg ". equals (parser. getName () {info. setMsg (parser. nextText () ;}/// move the parser to the next type = parser. next (); // close the stream is. close ();
tv_weather.setText(info.toString()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
The Pull parser is used to allow application code to actively retrieve events from the parser. Because it actively acquires events, it can jump out at any time.