android——使用pull解析xml文件

1、persons.xml

   将persons.xml文件放到src目录下。其代码如下:

 

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<persons>
	<person id="1">
		<name>范冰冰</name>
		<age>31</age>
	</person>
	<person id="2">
		<name>林志玲</name>
		<age>38</age>
	</person>
	<person id="3">
		<name>章泽天</name>
		<age>20</age>
	</person>
</persons>


2、Person

 

新建一个名叫Person的javabean,代码如下:

 

package com.njupt.xml1;

public class Person {

	private Integer id;
	private String name;
	private Integer age;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
	
	public Person() {
		super();
	}
	
	
	public Person(Integer id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	
	
}


 

3、PersonService

    在这里使用android中已经集成的pull来解析xml文件,代码如下:

 

package com.njupt.xml1;

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

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

public class PersonService {

	public List<Person> loadPersons(InputStream in) throws Exception{
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(in,"UTF-8");
		
		List<Person> persons = new ArrayList<Person>();
		Person p = null;
		
		for(int type = parser.getEventType() ; type != XmlPullParser.END_DOCUMENT; type = parser.next()){
			if( type == XmlPullParser.START_TAG){
				if( parser.getName().equals("person")){
					p = new Person();
					String id = parser.getAttributeValue(0);
					p.setId(Integer.parseInt(id));
					
					persons.add(p);
				}else if(parser.getName().equals("name")){
					String name = parser.nextText();
					p.setName(name);
					
				}else if(parser.getName().equals("age")){
					String age = parser.nextText();
					p.setAge(Integer.parseInt(age));
				}
               
				
			}
		}
		
		return persons;
	}
	
}


 

==================================================================

另附上android中测试时,xml中需要配置的两段代码:

 

 <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.njupt.xml1" />
    <uses-library android:name="android.test.runner" />


最后运行的结果是:

 



   

 

posted @ 2013-06-23 17:29  爱生活,爱编程  阅读(181)  评论(0编辑  收藏  举报