Extensible Markup Language (XML) 是一组将文档编码成机器可读形式的规则,也是一种在网络上共享数据的普遍格式。经常更新内容的网站比如新闻网站和博客上都提供XML feed来记录更新的信息,以便用户进行订阅读取。
解析器我们用XMLPullParser ,Android 官网推荐。如果对xml不熟悉可以先看下http://www.w3cschool.cc/xml/xml-tutorial.html;
今天写的demo是基于上次的AsyncTask之下载HTML的扩充 ,首先我写了一个persons.xml
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="1">
<name>Tom</name>
<age>21</age>
</person>
<person id="2">
<name>Rose</name>
<age>22</age>
</person>
<person id="3">
<name>Jack</name>
<age>20</age>
</person>
</persons>
之后我把它上传到了七牛云存储,地址http://carousel.qiniudn.com/persons.xml,可以直接点击查看,下载。
接下来在工程下写一个Person JavaBean:
public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Short getAge() {
return age;
}
public void setAge(Short age) {
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
private Integer id;
private String name;
private Short age;
}
在MainActivity加入 readXML():
public List<Person> readXML(InputStream inStream) {
// Log.i("LIST", "startReadXML");
//创建解析器对象,生成实例
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(inStream, "UTF-8");// 设置数据源编码
int eventType = parser.getEventType();// 获取事件类型
Person currentPerson = null;
List<Person> persons = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
persons = new ArrayList<Person>();// 实例化集合类
break;
case XmlPullParser.START_TAG:// 开始读取某个标签
// 通过getName判断读到哪个标签,然后通过nextText()获取文本节点值,或通过getAttributeValue(i)获取属性节点值
String name = parser.getName();
if (name.equalsIgnoreCase("person")) {
currentPerson = new Person();
currentPerson.setId(new Integer(parser
.getAttributeValue(null, "id")));
} else if (currentPerson != null) {
if (name.equalsIgnoreCase("name")) {
currentPerson.setName(parser.nextText());// 如果后面是Text元素,即返回它的值
Log.i("LIST", currentPerson.getName());
} else if (name.equalsIgnoreCase("age")) {
currentPerson.setAge(new Short(parser.nextText()));
}
}
break;
case XmlPullParser.END_TAG:// 结束元素事件
// 读完一个Person,可以将其添加到集合类中
if (parser.getName().equalsIgnoreCase("person")
&& currentPerson != null) {
persons.add(currentPerson);
currentPerson = null;
}
break;
}
eventType = parser.next();
}
inStream.close();
return persons;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
对于上次的downloadUrL() 末尾一点改动:
//获取InputSream
is = conn.getInputStream();
//把InputStream 转为 String
// String contentAsString = readIt(is, len);
StringBuilder strBuilder = new StringBuilder();
List<Person> list = readXML(is);
for (int i = 0; i < list.size(); i++) {
strBuilder.append("id:" + list.get(i).getId() + "\n");
strBuilder.append("name:" + list.get(i).getName() + "\n");
strBuilder.append("age:" + list.get(i).getAge() + "\n");
strBuilder.append("==========\n");
}
return strBuilder.toString();