importorg.xmlpull.v1.XmlPullParser;
importandroid.util.Xml;
importcn.itcast.xml.domain.Person;
public classPullXMLReader {
public staticList<Person> readXML(InputStream inStream) {
XmlPullParserparser = Xml.newPullParser();
try {
parser.setInput(inStream,"UTF-8");
int eventType =parser.getEventType();
PersoncurrentPerson = null;
List<Person>persons = null;
while (eventType!= XmlPullParser.END_DOCUMENT) {
switch (eventType){
caseXmlPullParser.START_DOCUMENT://文档开始事件,可以进行数据初始化处理
persons = newArrayList<Person>();
break;
caseXmlPullParser.START_TAG://开始元素事件
String name =parser.getName();
if(name.equalsIgnoreCase("person")) {
currentPerson =new Person();
currentPerson.setId(newInteger(parser.getAttributeValue(null, "id")));
} else if(currentPerson != null) {
if(name.equalsIgnoreCase("name")) {
currentPerson.setName(parser.nextText());//如果后面是Text元素,即返回它的值
} else if(name.equalsIgnoreCase("age")) {
currentPerson.setAge(newShort(parser.nextText()));
}
}
break;
caseXmlPullParser.END_TAG://结束元素事件
if(parser.getName().equalsIgnoreCase("person") && currentPerson!= null) {
persons.add(currentPerson);
currentPerson =null;
}
break;
}
eventType =parser.next();
}
inStream.close();
return persons;
} catch (Exceptione) {
e.printStackTrace();
}
return null;
}
}