package com.cyh.service; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; import android.util.Xml; import com.cyh.domain.Person; public class PersonService { /** * 解析XML Pull破解器方法 * @param xml * @return * @throws Exception */ public static List<Person> getPersons(InputStream xml) throws Exception{ List<Person> persons = null; Person person = null; // XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); XmlPullParser parser = Xml.newPullParser(); //为Pull破解器设置要解析的XML parser.setInput(xml,"UTF-8"); int event = parser.getEventType(); while(event != XmlPullParser.END_DOCUMENT){ switch (event){ case XmlPullParser.START_DOCUMENT: persons = new ArrayList<Person>(); break; case XmlPullParser.START_TAG: if("person".equals(parser.getName())){ person = new Person(); int id = Integer.parseInt(parser.getAttributeValue(0)); person.setId(id); } if("name".equals(parser.getName())){ String name = parser.nextText(); person.setName(name); } if("age".equals(parser.getName())){ int age = Integer.parseInt(parser.nextText()); person.setAge(age); } break; case XmlPullParser.END_TAG: if("person".equals(parser.getName())){ persons.add(person); person = null; } break; } event = parser.next(); } return persons; } /** * 保存数据到XML文件中 * @param list * @param out * @throws Exception */ public static void save(List<Person> list,OutputStream out) throws Exception{ XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(out,"UTF-8"); serializer.startDocument("UTF-8",true);//文档开始 serializer.startTag(null,"persons"); for(Person p:list){ serializer.startTag(null,"person"); serializer.attribute(null,"id",p.getId().toString()); serializer.startTag(null,"name"); serializer.text(p.getName()); serializer.endTag(null,"name"); serializer.startTag(null,"age"); serializer.text(p.getAge().toString()); serializer.endTag(null,"age"); serializer.endTag(null,"person"); } serializer.endTag(null,"persons"); serializer.endDocument();//文档结束 out.flush(); out.close(); } }