Android 开发工具类 12_PullXmlTools

xml 格式数据

 <?xml version="1.0" encoding="UTF-8"?>

 <user-list>
<user id="1">
<name>张三</name>
<age>22</age>
</user> <user id="2">
<name>李四</name>
<age>28</age>
</user> <user id="3">
<name>王五</name>
<age>32</age>
</user> </user-list>

XmlPullParserFactory 解析 xml 数据

 package com.example.dashu_xml;

 import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory; import android.R.integer; /**
* pull解析xml
* */
public class PullXmlTools {
public PullXmlTools() {
} /**
* inputStream通常为服务器端获取的io流 encode编码格式
*
* @throws XmlPullParserException
* @throws IOException
* @throws NumberFormatException
* */
public static List<User> parseXML(InputStream inputStream, String encode)
throws XmlPullParserException, NumberFormatException, IOException {
List<User> list = null;
User user = null;// 装载每一个节点的内容
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
// 获得xml解析类引用
XmlPullParser pullParser = factory.newPullParser();
pullParser.setInput(inputStream, encode);
// 获得事件类型
int eventType = pullParser.getEventType();
// 判定是否解析到文档结束
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:// 开始文档
list = new ArrayList<User>();
break;
case XmlPullParser.START_TAG:// 开始节点
if ("user".equals(pullParser.getName())) {
user = new User();
int id = Integer.parseInt(pullParser.getAttributeValue(
null, "id").toString());
user.setId(id);
}
if (user != null) {
if ("name".equals(pullParser.getName())) {
String name = pullParser.nextText().toString();
user.setName(name);
}
if ("age".equals(pullParser.getName())) {
int age = Integer.parseInt(pullParser.nextText()
.toString());// 取出id
user.setAge(age);
}
}
break;
case XmlPullParser.END_TAG:// 结束节点时候
if ("user".equals(pullParser.getName())) {
list.add(user);
user = null;
}
break;
default:
break;
}
eventType = pullParser.next();// 下一个解析标识
}
return list;
}
}

【参考文献】

http://blog.csdn.net/u010794950/article/details/24574627

上一篇:重温web服务器--细说Tomcat服务器


下一篇:kaptcha 验证码组件使用