// 解析数据
private void show(String strUrl) {
try {
URL url = new URL(strUrl);
// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
// 获得响应码
int code = connection.getResponseCode();
if (code == 200) {
InputStream is = connection.getInputStream();
// pull解析
XmlPullParser xmlParser = Xml.newPullParser();
// 设置编码
xmlParser.setInput(is, "UTF-8");
News n = null;
// 获取数据类型
int eventType = xmlParser.getEventType();
while (eventType != XmlResourceParser.END_DOCUMENT) {
// 通过getName判断读到哪个标签,然后通过nextText()获取文本节点值,或通过getAttributeValue(i)获取属性节点值
String tagName = xmlParser.getName();
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<News>();
break;
case XmlPullParser.START_TAG:
// 如果新闻标签的开始我们需要创建News对象
if ("item".equalsIgnoreCase(tagName)) {
n = new News();
} else if ("title".equals(tagName)) {
n.setTitle(xmlParser.nextText());
} else if ("link".equals(tagName)) {
n.setLink(xmlParser.nextText());
} else if ("imgs".equals(tagName)) {
n.setImgs(xmlParser.nextText());
} else if ("copyright".equals(tagName)) {
n.setCopyright(xmlParser.nextText());
} else if ("pubDate".equals(tagName)) {
n.setPubDate(xmlParser.nextText());
}
break;
case XmlPullParser.END_TAG:
if ("item".equals(tagName)) {
list.add(n);
Log.e("info", "++++++" + n);
n = null;
}
break;
case XmlPullParser.END_DOCUMENT:
break;
}
eventType = xmlParser.next();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
转载于:https://my.oschina.net/ymmymm/blog/720049