1 public static List<Person> getPersons(InputStream xml) throws Exception{ 2 List<Person> persons = null; 3 Person person = null; 4 XmlPullParser pullParser = Xml.newPullParser(); 5 pullParser.setInput(xml, "UTF-8");//为Pull解析器设置要解析的XML数据 6 int event = pullParser.getEventType(); 7 while(event != XmlPullParser.END_DOCUMENT){ 8 switch (event) { 9 case XmlPullParser.START_DOCUMENT: 10 persons = new ArrayList<Person>(); 11 break; 12 13 case XmlPullParser.START_TAG: 14 if("person".equals(pullParser.getName())){ 15 int id = new Integer(pullParser.getAttributeValue(0)); 16 person = new Person(); 17 person.setId(id); 18 } 19 if("name".equals(pullParser.getName())){ 20 String name = pullParser.nextText(); 21 person.setName(name); 22 } 23 if("age".equals(pullParser.getName())){ 24 int age = new Integer(pullParser.nextText()); 25 person.setAge(age); 26 } 27 break; 28 29 case XmlPullParser.END_TAG: 30 if("person".equals(pullParser.getName())){ 31 persons.add(person); 32 person = null; 33 } 34 break; 35 } 36 event = pullParser.next(); 37 } 38 return persons; 39 }
时间: 2024-11-03 05:33:31