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 [email protected]
*/
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;
}
}

你可能感兴趣的:(xml)