Android中使用PULL方式解析XML和XmlSerializer进行序列化

      XML解析方式一般有DOM解析,SAX解析,而Android中推荐的解析方式是PULL解析,以下是最近写的一个Demo中的关键代码。

import java.io.File;
import java.io.FileOutputStream;
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.os.Environment;
import android.util.Xml;

public class PersonXmlPullParserAndXmlSerializer {

	public ArrayList<Person> XmlPullParserTest() throws Exception {
		//创建一个InputStream通过反射得到当前累的对象然后getClassLoader().getResourceAsStream();
		InputStream is = PersonXmlPullParserAndXmlSerializer.class.getClassLoader().getResourceAsStream("persons.xml");
		//Xml.newPullParser()得到一个XmlPullParser
		XmlPullParser xpp = Xml.newPullParser();
		//设置要解析的目标和读取的编码
		xpp.setInput(is, "UTF-8");
		ArrayList<Person> listPerson = new ArrayList<Person>();
		Person p = null;
		for (int i = xpp.getEventType(); i != XmlPullParser.END_DOCUMENT; i = xpp.next()) {
			switch (i) {
			case XmlPullParser.START_TAG:
				if (xpp.getName() == "person") {
					String str = xpp.getAttributeValue(0);
					p = new Person();
					p.setId(Integer.parseInt(str));
				} else if (xpp.getName().equals("name")) {
					p.setName(xpp.nextText());
				} else if (xpp.getName().equals("age")) {
					p.setAge(Integer.parseInt(xpp.nextText()));
				}
				break;
			case XmlPullParser.END_TAG:
				//遍历Xml文件中一个对象,直到解析到这个对象的
				if (xpp.getName().equals("person")) {
					listPerson.add(p);
				}
				break;
			}
		}
		return listPerson;
	}

	public void XmlSerializerTest(List<Person> persons) throws Exception {
		OutputStream os = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "persons.xml"));
		XmlSerializer serializer = Xml.newSerializer();
		serializer.setOutput(os, "UTF-8");
		serializer.startDocument("UTF-8", true);
		serializer.startTag(null, "persons");
		for (Person person : persons) {
			serializer.startTag(null, "person");
			
			serializer.attribute(null, "id", person.getId().toString());

			serializer.startTag(null, "name");
			serializer.text(person.getName());
			serializer.endTag(null, "name");

			serializer.startTag(null, "age");
			serializer.text(person.getAge().toString());
			serializer.endTag(null, "age");

			serializer.endTag(null, "person");
		}
		serializer.endDocument();
	}
}
 

你可能感兴趣的:(Serialize)