XML解析的初步学习

XML解析的初步学习


weatherService页面,解析Xml

<infos>
    <city id="sh">
        <name>上海</name>
        <temp>20/30</temp>
    </city>
    <city id="xm">
        <name>厦门</name>
        <temp>25/30</temp>
    </city>
    <city id="fz">
        <name>福州</name>
        <temp>5/10</temp>
    </city>

</infos>
public class weatherService {
    public  static List<weatherinfo>getInfoFromXMl(InputStream is)throws  Exception{
        XmlPullParser parser = Xml.newPullParser();//得到pull解析器
        parser.setInput(is,"utf-8");//初始化解析器,第一个参数为xml数据
        List<weatherinfo>weatherinfos=null;
        weatherinfo weatherinfo=null;
        int type=parser.getEventType();//得到当前事件类型
        while (type!=XmlPullParser.END_DOCUMENT){
        switch (type){
            case XmlPullParser.START_TAG://节点的开始标签
                if ("infos".equals(parser.getName())){
                    weatherinfos=new ArrayList<>();
                }else if ("city".equals(parser.getName())){
                    weatherinfo=new weatherinfo();
                    weatherinfo.setId(parser.getAttributeValue(0));
                }else if ("name".equals(parser.getName())){
                    weatherinfo.setName(parser.nextText());
                }else if ("temp".equals(parser.getName())){
                    weatherinfo.setTemp(parser.nextText());
                }

                break;
            case XmlPullParser.END_TAG://节点的结束标签
                if ("city".equals(parser.getName())) {
                    weatherinfos.add(weatherinfo);
                }
                break;
        }
        type=parser.next();
    }
    return weatherinfos;
    }
}

MainActivity页面,对weatherService的获取

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        InputStream is= this.getResources().openRawResource(R.raw.weather);

        try {
            List<weatherinfo>infos= weatherService.getInfoFromXMl(is);
            weatherinfoMap=new HashMap<>();
            for (weatherinfo info:infos) {
              weatherinfoMap.put(info.getId(),info);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        getMap("xm");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值