Android系统中采用PULL技术解析XML文档比用SAX技术性能要好得多.建议Android的开发者采用PULL技术解析XML文档.跟SAX类似,只不过PULL技术返回的事件类型是整型,所以我们只要对返回的事件进行处理就行了.
java代码
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.ArrayList;
- import java.util.List;
- import org.xmlpull.v1.XmlPullParser;
- import org.xmlpull.v1.XmlSerializer;
- import android.util.Xml;
- import com.cn.domain.Persion;
- /****
- * 采用Pull解析XML
- *
- * ****/
- public class PULLPersionService {
- public static List<Persion> getPersino(InputStream is)throws Exception{
- List<Persion> list = null;
- Persion persion = null;
- XmlPullParser parser = Xml.newPullParser();
- parser.setInput(is, "UTF-8");
- int event = parser.getEventType();
- while(event != XmlPullParser.END_DOCUMENT){
- switch (event){
- case XmlPullParser.START_DOCUMENT:
- 30. list = new ArrayList<Persion>();
- break;
- case XmlPullParser.START_TAG:
- if("person".equals(parser.getName())){//得到指针所指向的节点名称
- int id = Integer.parseInt(parser.getAttributeValue(0));
- persion = new Persion();
- persion.setId(id);
- }
- if(persion != null){
- if("name".equals(parser.getName())){
- String name = parser.nextText();
- persion.setName(name);
- }else if("age".equals(parser.getName())){
- String age = parser.nextText();
- persion.setName(age);
- }
- }
- break;
- case XmlPullParser.END_TAG:
- if("person".equals(parser.getName())){
- list.add(persion);
- persion = null;
- }
- break;
- default:
- break;
- }
- }
- event = parser.next();
- return list;
- }
- public static void save(List<Persion> list,OutputStream os) throws IllegalArgumentException, IllegalStateException, IOException{
- XmlSerializer serializer = Xml.newSerializer();
- serializer.setOutput(os, "UTF-8");
- serializer.startDocument("UTF-8", true);
- serializer.startTag(null, "persons");
- for(Persion persion : list){
- serializer.startTag(null, "person");
- serializer.attribute(null, "id", String.valueOf(persion.getId()));
- serializer.startTag(null, "name");
- serializer.text(persion.getName());
- serializer.endTag(null, "name");
- serializer.startTag(null, "age");
- serializer.text(String.valueOf(persion.getAge()));
- serializer.endTag(null, "age");
- serializer.endTag(null, "person");
- }
- serializer.endTag(null, "persons");
- serializer.endDocument();
- os.flush();
- os.close();
- }
- }