一小段需要解析的XML文件
<?xml version="1.0" encoding="UTF-8"?> <infos> <city id="1"> <name>上海</name> <tianqi>多云转晴</tianqi> <feng>西北风3-4级</feng> </city> <city id="2"> <name>武汉</name> <tianqi>暴雨</tianqi> <feng>南风4-47级</feng> </city> <city id="3"> <name>日本</name> <tianqi>晴天</tianqi> <feng>西北风0-1级</feng> </city> </infos>
package service; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import android.util.Xml; public class servicewe { public static List<Wheatherin> getWheatherins(InputStream is)throws Exception{ XmlPullParser pareser=Xml.newPullParser(); pareser.setInput(is,"utf-8"); List<Wheatherin> wheatherin=null; Wheatherin wheatherino =null; int type=pareser.getEventType(); while(type!=XmlPullParser.END_DOCUMENT){ switch(type){ case XmlPullParser.START_TAG: if("infos".equals(pareser.getName())){ wheatherin = new ArrayList<Wheatherin>(); }else if("city".equals(pareser.getName())){ wheatherino =new Wheatherin(); String isds=pareser.getAttributeValue(0); wheatherino.setId(Integer.parseInt(isds)); }else if("name".equals(pareser.getName())){ String name =pareser.nextText(); wheatherino.setName(name); }else if("tianqi".equals(pareser.getName())){ String tianqi =pareser.nextText(); wheatherino.setTianqi(tianqi); }else if("feng".equals(pareser.getName())){ String feng =pareser.nextText(); wheatherino.setFeng(feng); } break; case XmlPullParser.END_TAG: if("dity".equals(pareser.getName())){ wheatherin.add(wheatherino); wheatherino=null; } break; } type=pareser.next(); } return wheatherin; } }
tv=(TextView)findViewById(R.id.tv); try { List<Wheatherin> in = servicewe.getWheatherins(MainActivity.class.getClassLoader().getResourceAsStream("whater.xml")); StringBuffer sb=new StringBuffer(); for(Wheatherin ins:in){ String ser=ins.toString(); sb.append(ser); sb.append("\n"); } tv.setText(sb); } catch (Exception e) { e.printStackTrace(); Toast.makeText(getApplicationContext(),"天气解析失败",0).show(); } }