Pull解析器解析XML文件

前端之家收集整理的这篇文章主要介绍了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>
原文链接:https://www.f2er.com/xml/296942.html

猜你在找的XML相关文章