Android入门:Pull解析XML


一、Pull解析器介绍


pull解析类似于SAX\DOM,都是用来解析XML的方法;


二、使用Pull解析器读取XML数据


模板代码如下:

XmlPullParser parser = Xml.newPullParser();   //创建一个PULL解析器
parser.setInput(in,"UTF-8");      //读取的编码为UTF-8
int event = parser.getEventType();   //开始解析时调用
while(event!=XmlPullParser.END_DOCUMENT){
	//parser.getName();   //获得当前指向的标签的标签名
	//parser.getAttributeValue(0);  //获得当前指向的标签的第1个属性值
	//parser.nextText(); //获得当前标签的标签值
	switch(event){
		case XmlPullParser.START_DOCUMENT: //如果指向的是START_DOCUMENT
		//处理
		break;
		case XmlPullParser.START_TAG:    //如果指向的是START_TAG
		//处理
		break;
		case XmlPullParser.END_TAG:     //如果指向的是END_TAG
		//处理
		break;
	}
	event = parser.next();     //指向下一个标签
}


应用:读取/data/data/package/files/目录下的person.xml文件


XML文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="1">
        <name>xiazdong-1</name>
        <age>20</age>
    </person>
    <person id="2">
        <name>xiazdong-2</name>
        <age>30</age>
    </person>
</persons>

从上面可以看出,<person></person>可以看做一个JavaBean,而<persons></persons>组成了一个person队列;

因此我们创建一个Person的JavaBean:

package org.xiazdong.vo;

public class Person {
	private int id;
	private String name;
	private int age;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Person(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public Person() {
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

}

接下来,我们编写如下readXML方法,使得将XML文件中的数据变成一个person队列;

public class XmlService {
	public List<Person> readXml(InputStream in) throws Exception {
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(in, "UTF-8");
		List<Person> list = null;
		Person person = null;
		int event = parser.getEventType();  //开始解析,并获取事件
		/*
		 * 可选事件包括:
		 * (1)START_DOCUMENT
		 * (2)END_DOCUMENT
		 * (3)START_TAG
		 * (4)END_TAG
		 * */
		while (event != XmlPullParser.END_DOCUMENT) {
			switch (event) {
			case XmlPullParser.START_DOCUMENT:
				list = new ArrayList<Person>();
				break;
			case XmlPullParser.START_TAG:
				if ("person".equals(parser.getName())) {
					person = new Person();
					int id = Integer.parseInt(parser.getAttributeValue(0));
					person.setId(id);
				}
				if("name".equals(parser.getName())){
					person.setName(parser.nextText());
				}
				if("age".equals(parser.getName())){
					person.setAge(Integer.parseInt(parser.nextText()));
				}
				break;
			case XmlPullParser.END_TAG:
				if("person".equals(parser.getName()))
					list.add(person);
				break;
			}
			event = parser.next();  //读取下一个
		}
		return list;
	}
}

编写好此方法之后,我们可以测试此方法:

public class XmlTest extends AndroidTestCase{
	private static final String TAG = "XmlTest";
	public void testRead() throws Exception{
		XmlService service = new XmlService();
		List<Person> list = service.readXml(this.getContext().openFileInput("person.xml"));
		Log.i(TAG, String.valueOf(list.size()));
		for(Person p:list){
			Log.i(TAG, p.toString());
		}
	}
}


运行效果如下:




三、使用Serializer解析器写入XML文件


核心代码如下:

XmlSerializer serializer = Xml.newSerializer();    //创建一个Serializer解析器
serializer.setOutput(out,"utf-8");      //设置输出流及输出的编码为UTF-8
serializer.startDocument("UTF-8",true);   //输出开始文档<?xml version="1.0" encoding="UTF-8" standalone="true"?>
serializer.startTag(null,"tagname");   //输出<tagname>
serializer.attribute(null,"name","value");  //输出<tagname name="value">
serializer.text("value");    //输出<tagname></tagname>
serializer.endTag(null,"tagname");//结束标签
serializer.endDocument();//结束文档

应用:创建上面提到的person.xml文件到/data/data/package/files中



以下代码用于将person队列写入输出流文件(此处为文件输出流)

public class XmlService {	
	public void writeXml(List<Person> list,OutputStream out)throws Exception{
		XmlSerializer serializer = Xml.newSerializer();
		serializer.setOutput(out, "UTF-8");
		serializer.startDocument("UTF-8", true);
		serializer.startTag(null, "persons");
		for(Person p:list){
			serializer.startTag(null,"person");
			serializer.attribute(null, "id", String.valueOf(p.getId()));
			serializer.startTag(null, "name");
			serializer.text(p.getName());
			serializer.endTag(null, "name");
			serializer.startTag(null, "age");
			serializer.text(p.getAge()+"");
			serializer.endTag(null, "age");
			serializer.endTag(null, "person");
		}
		serializer.endTag(null, "persons");
		serializer.endDocument();
		out.flush();
		out.close();
	}
}


测试代码如下:

public class XmlTest extends AndroidTestCase{	
	public void testWrite()throws Exception{
		XmlService service = new XmlService();
		List<Person> list = new ArrayList<Person>();
		for(int i=0;i<3;i++){
			Person p = new Person();
			p.setId(i);
			p.setName("xiazdong-"+i);
			p.setAge(20+i);
			list.add(p);
		}
		OutputStream out = this.getContext().openFileOutput("person.xml", Context.MODE_PRIVATE);
		service.writeXml(list, out);
	}
}

总结:使用Pull解析器读取,使用Serializer写入;









你可能感兴趣的:(android)