Pull解析器解析XML文件

package com.study.service;

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

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import com.study.domain.Person;

public class PersonService {
	public 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())) {
					int id = new Integer(pullParser.getAttributeValue(0));
					person = new Person();
					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:
				persons.add(person);
				person = null;
			}
			event = pullParser.next();
		}
		return persons;
	}
}

package com.study.domain;

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;
	}
}

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="23">
        <name>lining</name>
        <age>30</age>
    </person>
    <person id="20">
        <name>tianchenglin</name>
        <age>21</age>
    </person>
</persons>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值