采用PULL解析器解析xml文件
package lee.service;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import org.xmlpull.v1.XmlPullParser;import android.util.Xml;import lee.vo.Person;public class XMLPullService {public List<Person> readXML(InputStream inStream) throws Exception{List<Person> persons = null;Person person = null;XmlPullParser pullParser = Xml.newPullParser();//获取Pull解析器 Xml.newPullParser()添加一个pullParser解析器带命名空间的支持pullParser.setInput(inStream, "UTF-8");//设置Pull解析器进行解析的XML内容int event = pullParser.getEventType();//获取第一个事件while(event!=XmlPullParser.END_DOCUMENT)//如果还不是结束文档事件,迭代每一个元素{switch (event){case XmlPullParser.START_DOCUMENT://开始文档事件persons = new ArrayList<Person>();break;case XmlPullParser.START_TAG://开始元素事件if("person".equals(pullParser.getName()))//pullParser.getName()得到当前指针所指向的节点的名称{person = new Person();int id = new Integer(pullParser.getAttributeValue(0));person.setId(id);}if(person!=null){if("name".equals(pullParser.getName())){String name = pullParser.nextText();//得到当前节点下一个文本节点的内容------> <name>liming</name> 得到limingperson.setName(name);}else if("age".equals(pullParser.getName())){String age = pullParser.nextText();//获取下一个Text类型节点的值person.setAge(new Short(age));}}break;case XmlPullParser.END_TAG://结束元素事件if("person".equals(pullParser.getName())){persons.add(person);person = null;}break;}event = pullParser.next();//进入下一个元素并触发相应事件}return persons;}}
?