XmlPull解析

public static List<Person> parseXml(InputStream inStream)  
            throws XmlPullParserException, IOException {  
        List<Person> persons = null;  
        Person person = null;  
        // 使用Android提供的Xml创建pull解析器  
        XmlPullParser xmlPullParser = Xml.newPullParser();  
        // 设置流文件  
        xmlPullParser.setInput(inStream, "UTF-8");  
        // 产生第一个事件  
        int eventType = xmlPullParser.getEventType();  
        while (eventType != XmlPullParser.END_DOCUMENT) {// 如果不是文档末尾  
 
            String tag = xmlPullParser.getName();//获取节点名  
            Log.i(TAG, tag+"====>");  
            switch (eventType) {  
            case XmlPullParser.START_DOCUMENT:  
                persons = new ArrayList<Person>();  
                break;  
            case XmlPullParser.START_TAG:  
                if ("person".equals(tag)) {  
                    person = new Person();  
                    person.setPersonId(Integer.valueOf(xmlPullParser.getAttributeValue(0)));  
                } else if ("name".equals(tag)) {  
                    //注意:这里获取文本元素是通过nextText()不是getText()  
                    person.setPersonName(xmlPullParser.nextText());  
                } else if ("age".equals(tag)) {  
                    person.setPersonAge(Integer.valueOf(xmlPullParser.nextText()));  
                }  
                break;  
            case XmlPullParser.END_TAG:  
                if("person".equals(tag))  
                    persons.add(person);  
                break;  
            }  
            eventType = xmlPullParser.next();// 推进到下一个元素,并触发事件  
        }  
        return persons;  
    } 

你可能感兴趣的:(pull)