pull解析xml

xml文件

<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name>zhansan</name>
<age>30</age>
</person>
<person id="20">
<name>lisi</name>
<age>25</age>
</person>
</persons>

 

/**

* pull解析
*
* @time 下午07:11:11
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class PullPersonService {
public static void save(List<Person> persons, OutputStream outputStream) throws Throwable {
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(outputStream, "utf-8");


serializer.startDocument("utf-8", true);
serializer.startTag(null, "persons");
for (Person p : persons) {
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());
serializer.endTag(null, "age");


serializer.endTag(null, "person");
}
serializer.endTag(null, "persons");
serializer.endDocument();
outputStream.close();
}


/**
* 取得每一个person元素
*
* @param inputStream
* @return
* @throws Throwable
*/
public static List<Person> getPersons(InputStream inputStream) throws Throwable {
List<Person> persons = null;
Person person = null;
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inputStream, "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(Integer.parseInt(parser.getAttributeValue(0)));
}
if (person != null) {
if ("name".equals(name)) {
person.setName(parser.nextText());
}
if ("age".equals(name)) {
person.setAge(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
if ("person".equals(parser.getName())) {
persons.add(person);
}
break;
}
eventType = parser.next();
}
return persons;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值