xml 格式数据
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <user-list> 4 <user id="1"> 5 <name>张三</name> 6 <age>22</age> 7 </user> 8 9 <user id="2"> 10 <name>李四</name> 11 <age>28</age> 12 </user> 13 14 <user id="3"> 15 <name>王五</name> 16 <age>32</age> 17 </user> 18 19 </user-list>
XmlPullParserFactory 解析 xml 数据
1 package com.example.dashu_xml; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.ArrayList; 6 import java.util.List; 7 8 import org.xmlpull.v1.XmlPullParser; 9 import org.xmlpull.v1.XmlPullParserException; 10 import org.xmlpull.v1.XmlPullParserFactory; 11 12 import android.R.integer; 13 14 /** 15 * pull解析xml 16 * */ 17 public class PullXmlTools { 18 public PullXmlTools() { 19 } 20 21 /** 22 * inputStream通常为服务器端获取的io流 encode编码格式 23 * 24 * @throws XmlPullParserException 25 * @throws IOException 26 * @throws NumberFormatException 27 * */ 28 public static List<User> parseXML(InputStream inputStream, String encode) 29 throws XmlPullParserException, NumberFormatException, IOException { 30 List<User> list = null; 31 User user = null;// 装载每一个节点的内容 32 XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 33 // 获得xml解析类引用 34 XmlPullParser pullParser = factory.newPullParser(); 35 pullParser.setInput(inputStream, encode); 36 // 获得事件类型 37 int eventType = pullParser.getEventType(); 38 // 判定是否解析到文档结束 39 while (eventType != XmlPullParser.END_DOCUMENT) { 40 switch (eventType) { 41 case XmlPullParser.START_DOCUMENT:// 开始文档 42 list = new ArrayList<User>(); 43 break; 44 case XmlPullParser.START_TAG:// 开始节点 45 if ("user".equals(pullParser.getName())) { 46 user = new User(); 47 int id = Integer.parseInt(pullParser.getAttributeValue( 48 null, "id").toString()); 49 user.setId(id); 50 } 51 if (user != null) { 52 if ("name".equals(pullParser.getName())) { 53 String name = pullParser.nextText().toString(); 54 user.setName(name); 55 } 56 if ("age".equals(pullParser.getName())) { 57 int age = Integer.parseInt(pullParser.nextText() 58 .toString());// 取出id 59 user.setAge(age); 60 } 61 } 62 break; 63 case XmlPullParser.END_TAG:// 结束节点时候 64 if ("user".equals(pullParser.getName())) { 65 list.add(user); 66 user = null; 67 } 68 break; 69 default: 70 break; 71 } 72 eventType = pullParser.next();// 下一个解析标识 73 } 74 return list; 75 } 76 }
【参考文献】
http://blog.csdn.net/u010794950/article/details/24574627