1. First attach the XML data to parse

<? The XML version = "1.0" encoding = "utf-8"? > < weather > < city > < name > xian < / name > < temp > 23 < / temp > < pm25 > 40 < / pm25 > < city > < city > < name > zhengzhou < / name > < temp > 26 < / temp > < pm25 > 100 < / pm25 > < city > < city > < name >, and < / name > < temp > and < / temp > < pm25 > 800 < / pm25 > < city > < / weather >Copy the code

2. Design javabeans based on the results of XML

package domain; public class City { private String name; private String temp; private String pm25; 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 getPm25() { return pm25; } public void setPm25(String pm25) { this.pm25 = pm25; } @Override public String toString() { return "City [name=" + name + ", temp=" + temp + ", pm25=" + pm25 + "]"; }}Copy the code

3. Click the button to start parsing

import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import android.app.Activity; import android.os.Bundle; import android.util.Xml; import android.view.View; import domain.City; public class MainActivity extends Activity { List<City> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View v){InputStream is = getClassLoader().getResourceasStream ("weather.xml"); XmlPullParser parser = xml.newpullParser (); Try {// Initialize parser.setInput(is, "utF-8 "); // Get the event type of the current node int type = parser.geteventType (); City city = null; // Parsing while(type! = XmlPullParser.END_DOCUMENT){ switch (type) { case XmlPullParser.START_TAG: If ("weather".equals(parser.getName())){list = new ArrayList<City>(); }else if("city".equals(parser.getName())){ city = new City(); }else if("name".equals(parser.getName())){// Get the text of the next node and move the pointer to the end node of the current node city.setName(parser.nexttext ()); }else if("temp".equals(parser.getName())){ city.setTemp(parser.nextText()); }else if("pm25".equals(parser.getName())){ city.setPm25(parser.nextText()); } break; case XmlPullParser.END_TAG: if("city".equals(parser.getName())){ list.add(city); } break; } type = parser.next(); } }catch(Exception e){ e.printStackTrace(); } for (City City: list) {system.out.println (city.tostring ()); }}}Copy the code