- package com.cn.service;
- 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:
- 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();
- }
- }
Pull解析技术
最新推荐文章于 2024-09-11 01:15:07 发布