android中xml的pull解析

xml的pull解析:


   //类加载器加载xml文件

InputStream is = MainActivity.class.getClassLoader().getResourceAsStream("weather.xml");

    //生成xml的pull解析器

    XmlPullParser pull = Xml.newPullParser();

    try {

    //设置输入流

pull.setInput(is, "utf-8");

        //解析器当前处于的状态

int type = pull.getEventType();

Weather weather = null ;

while (type != XmlPullParser.END_DOCUMENT) {

switch (type) {

            //当前是开始标签的节点

    case XmlPullParser.START_TAG:

                //拿到节点标签的名字

        String name = pull.getName();

            //判断节点标签的名字 (下面同这儿),然后放到weather对象中  

        if("channel".equals(name)){

            weather = new Weather();

            weather.setId(pull.getAttributeValue(0));

        }

            

        if("city".equals(name)){

            weather.setName(pull.nextText());

        }

        if("temp".equals(name)){

            weather.setTemp(pull.nextText());

        }

        if("wind".equals(name)){

            weather.setWind(pull.nextText());

        }

        break;

        //如果是结束标签的节点,此处将weather对象放入list集合保存

case XmlPullParser.END_TAG:

    String tagname = pull.getName();

    if("channel".equals(tagname)){

        list.add(weather);

    }

default:

    break;

        }

//此处必须写,否则不会向下执行

        type = pull.next();

        }

    } catch (Exception e) {

e.printStackTrace();

    }

}



你可能感兴趣的:(android中xml的pull解析)