标签:android style blog io ar color os sp java
<?xml version=‘1.0‘ encoding=‘utf-8‘ standalone=‘yes‘ ?> <weather> <city> <name>深圳</name> <temp>18°</temp> <pm25>30</pm25> </city> <city> <name>上海</name> <temp>13°</temp> <pm25>25</pm25> </city> <city> <name>北京</name> <temp>6°</temp> <pm25>800</pm25> </city> </weather>
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; } public City(String name, String temp, String pm25) { super(); this.name = name; this.temp = temp; this.pm25 = pm25; } public City() { super(); } @Override public String toString() { return "City [name=" + name + ", temp=" + temp + ", pm25=" + pm25 + "]"; } }
public class MainActivity extends Activity { List<City> cityList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View v){ //解析xml文件 //1. 拿到资源文件 InputStream is = getClassLoader().getResourceAsStream("weather.xml"); //2. 拿到解析器对象 XmlPullParser xp = Xml.newPullParser(); try { //3. 初始化xp对象 xp.setInput(is, "gbk");//根据文件保存的编码决定 //4.开始解析 //获取当前节点的事件类型 int type = xp.getEventType(); City city = null; while(type != XmlPullParser.END_DOCUMENT){ //判断当前解析到哪一个节点,从而确定你要做什么操作 switch (type) { case XmlPullParser.START_TAG: // 获取当前节点的名字 if("weather".equals(xp.getName())){ cityList = new ArrayList<City>(); } else if("city".equals(xp.getName())){ city = new City(); } else if("name".equals(xp.getName())){ // 获取当前节点的下一个节点的文本,把指针移动到当前节点的结束节点 String name = xp.nextText(); city.setName(name); } else if("temp".equals(xp.getName())){ // 获取当前节点的下一个节点的文本,把指针移动到当前节点的结束节点 String temp = xp.nextText(); city.setTemp(temp); } else if("pm25".equals(xp.getName())){ // 获取当前节点的下一个节点的文本,把指针移动到当前节点的结束节点 String pm25 = xp.nextText(); city.setPm25(pm25); } break; case XmlPullParser.END_TAG: if("city".equals(xp.getName())){ cityList.add(city); } break; } //把指针移动到下一个节点 type = xp.next(); } for (City c : cityList) { System.out.println(c.toString()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Android基础--XML解析(XmlPullParser )
标签:android style blog io ar color os sp java
原文地址:http://www.cnblogs.com/fujianyi/p/4111797.html