Android中使用XmlPullParse解析xml文件

解析xml文件有很多方法,有SAX,还有DOM,在android中,android自带了XmlPullParse相关包,

在android中要解析xml文件,推荐使用XmlPullParse解析。

下面是一个使用的相关案例:

PersonService:

package com.example.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import android.content.Intent;
import android.util.Xml;

import com.example.domain.Person;

public class PersonService {

	public static List<Person> getPersons(InputStream xml) throws Exception{
		List<Person> persons = null;
		Person person = null;
		XmlPullParser pullParser = Xml.newPullParser();
		pullParser.setInput(xml, "UTF-8");
		
		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())){
					person = new Person();
					//这是获得字段的属性
					int id = new Integer(pullParser.getAttributeValue(0));
					person.setId(id);
				}
				if("name".equals(pullParser.getName())){
					//获得其中的内容
					String name = pullParser.nextText();
					person.setName(name);
				}
				if("age".equals(pullParser.getName())){
					int age = new Integer(pullParser.nextText());
					person.setAge(age);
				}
				break;
			case XmlPullParser.END_TAG:
				if("person".equals(pullParser.getName())){
					persons.add(person);
					person = null;
				}
				break;
			default:
				break;
			}
			event = pullParser.next();
		}
		return persons;
	}
}

将xml文件放在类路径目录下,编写测试案例:

package cn.example.test;

import java.io.InputStream;
import java.util.List;

import android.test.AndroidTestCase;
import android.util.Log;

import com.example.domain.Person;
import com.example.service.PersonService;

public class PersonServiceTest extends AndroidTestCase {

	public void testPersonXml() throws Exception{
		InputStream xml = this.getClass().getClassLoader().getResourceAsStream("person.xml");
		List<Person> persons = PersonService.getPersons(xml);
		
		for(Person person:persons){
			Log.d("TAG", person.toString());
		}
	}
}
xml文件:

<?xml version="1.0" encoding="utf-8"?>
<Persons>
    <person id="1">
        <name>zhangsan</name>
        <age>12</age>
    </person>
    <person id="2">
        <name>lisi</name>
        <age>22</age>
    </person>
</Persons>


测试结果:

12-26 07:15:45.022: D/TAG(10150): Person [id=1, name=zhangsan, age=12]

12-26 07:15:45.022: D/TAG(10150): Person [id=2, name=lisi, age=22]


你可能感兴趣的:(Android中使用XmlPullParse解析xml文件)