/**
* 采用Pull解析XML内容
*/
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.android.mldn.domain.Person;
public class PULLPersonService {
public static void save (List<Person> persons,OutputStream outStream)
throws Throwable{
//创建一个序列化实例
XmlSerializer serializer = Xml.newSerializer();
//设置输出流
serializer.setOutput(outStream, "UTF-8");
//开始文档
serializer.startDocument("UTF-8", true);
//开始元素
serializer.startTag(null, "persons");
for (Person person : persons) {
//person 元素节点
serializer.startTag(null, "person");
//设置属性
serializer.attribute(null, "id", person.getId().toString());
//name 元素节点 开始
serializer.startTag(null, "name");
//设置文本节点属性
serializer.text(person.getName());
//name 元素节点 结束
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text(person.getAge().toString());
serializer.endTag(null, "age");
//person 元素节点 结束
serializer.endTag(null, "person");
}
//结束元素
serializer.endTag(null, "persons");
//结束文档
serializer.endDocument();
outStream.flush();
outStream.close();
}
public static List<Person> getPersons(InputStream inStream)
throws Throwable{
List<Person> persons = null;
Person person = null;
//创建Pull 解析器实例
XmlPullParser parser = Xml.newPullParser();
//读取xml 文件数据
parser.setInput(inStream,"UTF-8");
//产生第一个事件
int eventType = parser.getEventType();
//只要不是文档结束事件
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
persons = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG:
//获取解析器当前指向的元素的名称
String name = parser.getName();
if ("person".equals(name)) {
person = new Person();
person.setId(new Integer(parser.getAttributeValue(0)));
}if (person!=null) {
if ("name".equals(name)) {
//获取解析器当前指向元素的下一个文本节点的值
person.setName(parser.nextText());
}if ("age".equals(name)) {
person.setAge(new Short(parser.nextText()));
}
}
break;
case XmlPullParser.END_TAG:
if ("person".equals(parser.getName())) {
persons.add(person);
person = null;
}
break;
}
//指向下一个 START_DOCUMENT
eventType = parser.next();
}
return persons;
}
}