Pull解析和生成XML文件
4、package com.wynlink.service;import java.io.InputStream;import java.io.Writer;import java.util.ArrayList;import java.util.List;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlSerializer;import android.util.Xml;import com.wynlink.domain.Person;/** * pull方式解析XML * @author yaodaqing * */public class PullPersonService {/** * 写数据到XML文件中 * 这里用Writer写入器。当然用流也可以 * 利用StringBuffer或StringBuilder来拼装XML * 此做法是面向对象的做法 */public static void writeXml(List<Person> persons,Writer writer) throws Exception{XmlSerializer serializer = Xml.newSerializer();serializer.setOutput(writer);//这里可以接受Writer和OutPutStringserializer.startDocument("UTF-8", true);//开始文档serializer.startTag(null, "persons");//开始标签;如果没有命名空间,则填nullfor(Person person : persons){serializer.startTag(null, "person");serializer.attribute(null, "id", String.valueOf(person.getId()));serializer.startTag(null, "name");serializer.text(person.getName());serializer.endTag(null, "name");serializer.startTag(null, "age");serializer.text(String.valueOf(person.getAge()));serializer.endTag(null, "age");serializer.endTag(null, "person");}serializer.endTag(null, "persons");//结束标签serializer.endDocument();writer.flush();writer.close();}/** * 从XML文件中读取数据 * @param inStream * @return * @throws Exception */public static List<Person> readxml(InputStream inStream) throws Exception {List<Person> persons = null;XmlPullParser parser = Xml.newPullParser();parser.setInput(inStream, "UTF-8");int eventCode = parser.getEventType();//事件Person person = null;while(eventCode != XmlPullParser.END_DOCUMENT){//只要事件不等于结束标签,则一直向下读取switch (eventCode) {case XmlPullParser.START_DOCUMENT://文档开始事件persons = new ArrayList<Person>();break;case XmlPullParser.START_TAG://开始元素if("person".equals(parser.getName())){person = new Person();person.setId(new Integer(parser.getAttributeValue(0)));} else if(person != null){if("name".equals(parser.getName())){person.setName(parser.nextText());} else if("age".equals(parser.getName())){person.setAge(new Short(parser.nextText()));}}break;case XmlPullParser.END_TAG://结束元素if("person".equals(parser.getName()) && person != null){persons.add(person);person = null;}break;}eventCode = parser.next();}return persons;}}