Xml对象:
1 /** 2 * 获取数据 3 * @param xml 4 * @return 5 * @throws Exception 6 */ 7 public static List<Person> getPersons(InputStream xml) throws Exception 8 { 9 List<Person> persons = null; 10 Person person = null; 11 12 XmlPullParser pullParser = Xml.newPullParser(); 13 pullParser.setInput(xml, "UTF-8");//为Pull解析器设置要解析的XML数据 14 int event = pullParser.getEventType(); 15 16 while(event != XmlPullParser.END_DOCUMENT) 17 { 18 switch (event) 19 { 20 case XmlPullParser.START_DOCUMENT: 21 persons = new ArrayList<Person>(); //<?xml version = "1.0" encoding = "UTF-8"> 22 break; 23 24 case XmlPullParser.START_TAG: 25 26 if("person".equals(pullParser.getName())){ 27 int id = new Integer(pullParser.getAttributeValue(0)); 28 person = new Person(); 29 person.setId(id); 30 } 31 if(person != null) 32 { 33 if("name".equals(pullParser.getName())) 34 { 35 String name = pullParser.nextText(); 36 person.setName(name); 37 } 38 if("age".equals(pullParser.getName())) 39 { 40 int age = new Integer(pullParser.nextText()); 41 person.setAge(age); 42 } 43 } 44 45 break; 46 47 case XmlPullParser.END_TAG: 48 if("person".equals(pullParser.getName())){ 49 persons.add(person); 50 person = null; 51 } 52 break; 53 }//switch 54 event = pullParser.next(); 55 } 56 return persons; 57 }
用Pull解析器生成数据
1 /** 2 * 保存数据 3 * @param persons 数据 4 * @param out 输出方向 5 * @throws Exception 6 */ 7 public static void save(List<Person> persons, OutputStream out) throws Exception{ 8 9 XmlSerializer serializer = Xml.newSerializer(); 10 serializer.setOutput(out, "UTF-8"); 11 serializer.startDocument("UTF-8", true); 12 serializer.startTag(null, "persons"); 13 14 for(Person person : persons) 15 { 16 serializer.startTag(null, "person"); 17 serializer.attribute(null, "id", person.getId().toString()); 18 19 serializer.startTag(null, "name"); 20 serializer.text(person.getName()); 21 serializer.endTag(null, "name"); 22 23 serializer.startTag(null, "age"); 24 serializer.text(person.getAge().toString()); 25 serializer.endTag(null, "age"); 26 27 serializer.endTag(null, "person"); 28 } 29 30 serializer.endTag(null, "persons"); 31 serializer.endDocument(); 32 out.flush(); 33 out.close(); 34 } 35 }
利用类加载器获取项目里的XML文件
1 public void testPersons() throws Exception{ 2 3 InputStream xml = this.getClass().getClassLoader().getResourceAsStream("person.xml"); 4 List<Person> persons = PersonService.getPersons(xml); 5 for(Person person : persons){ 6 Log.i(TAG, person.toString()); 7 } 8 }