package com.ljq.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 com.ljq.entity.Person;
import android.util.Xml;
/**
* Pull解析xml文件
*
* @author jiqinlin
*
*/
public class PullPersonService {
/**
* 使用pull解析器生成xml文件
*
* @param persons
* @param writer
* @return
*/
public static String writeXML(List persons, Writer writer){
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);
//第一个参数为命名空间,如果不使用命名空间,可以设置为null
serializer.startTag("", "persons");
for (Person person : persons){
serializer.startTag("", "person");
serializer.attribute("", "id", person.getId().toString());
serializer.startTag("", "name");
serializer.text(person.getName());
serializer.endTag("", "name");
serializer.startTag("", "age");
serializer.text(person.getAge().toString());
serializer.endTag("", "age");
serializer.endTag("", "person");
}
serializer.endTag("", "persons");
serializer.endDocument();
} catch (Exception e) {
e.printStackTrace();
}
return writer.toString();
}
/**
* 使用pull解析器解析xml文件
*
* @param inStream
* @return
* @throws Exception
*/
public static List readXML(InputStream inStream) throws Exception {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inStream, "UTF-8");
int eventType = parser.getEventType();
Person currentPerson = null;
List persons = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
persons = new ArrayList();
break;
case XmlPullParser.START_TAG:// 开始元素事件
String name = parser.getName();
if (name.equalsIgnoreCase("person")) {
currentPerson = new Person();
currentPerson.setId(new Integer(parser.getAttributeValue(null, "id")));
} else if (currentPerson != null) {
if (name.equalsIgnoreCase("name")) {
currentPerson.setName(parser.nextText());// 如果后面是Text元素,即返回它的值
} else if (name.equalsIgnoreCase("age")) {
currentPerson.setAge(new Short(parser.nextText()));
}
}
break;
case XmlPullParser.END_TAG:// 结束元素事件
if (parser.getName().equalsIgnoreCase("person")&& currentPerson != null) {
persons.add(currentPerson);
currentPerson = null;
}
break;
}
eventType = parser.next();
}
inStream.close();
return persons;
}
}