利用pull解析Xml
发布时间:2020-12-16 09:19:49 所属栏目:百科 来源:网络整理
导读:一小段需要解析的XML文件 ?xml version="1.0" encoding="UTF-8"?infos city id="1"name上海/nametianqi多云转晴/tianqifeng西北风3-4级/feng /city city id="2"name武汉/nametianqi暴雨/tianqifeng南风4-47级/feng /city city id="3"name日本/nametianqi晴天
一小段需要解析的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(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |