JavaSE|Android(网络:获取XML格式数据)

【JavaSE|Android(网络:获取XML格式数据)】public class News {
private Integer id;
private String title;
private Integer timelength;
...

}

ListView listView = (ListView) this.findViewById(R.id.listView);
try {
List videos = VideoNewsService.getLastNews(); //需修改成你本机的Http请求路径
List data = https://www.it610.com/article/new ArrayList();
for(News news : videos){
HashMap item = new HashMap();
item.put("id", news.getId());
item.put("title", news.getTitle());
item.put("timelength", getResources().getString(R.string.timelength)
+ news.getTimelength()+ getResources().getString(R.string.min));
data.add(item);
}
SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
new String[]{"title", "timelength"}, new int[]{R.id.title, R.id.timelength});
listView.setAdapter(adapter);






public static List getLastNews() throws Exception{
String path = "http://192.168.0.168:8080/web/ListServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
InputStream inStream = conn.getInputStream();
return parseXML(inStream);
}
return null;
}
/**
* 解析服务器返回的xml数据



喜羊羊与灰太狼全集 - 锐客网
90


老张与灰太狼 - 锐客网
20


老方与LILI - 锐客网
30


* @param inStream
* @return
*/
private static List parseXML(InputStream inStream) throws Exception {
List newses = new ArrayList();
News news = null;
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inStream, "UTF-8");
int event = parser.getEventType();
while( event != XmlPullParser.END_DOCUMENT){
switch (event) {
case XmlPullParser.START_TAG:
if("news".equals(parser.getName())){
int id = new Integer(parser.getAttributeValue(0));
news = new News();
news.setId(id);
}else if("title".equals(parser.getName())){
news.setTitle(parser.nextText());
}else if("timelength".equals(parser.getName())){
news.setTimelength(new Integer(parser.nextText()));
}
break;

case XmlPullParser.END_TAG:
if("news".equals(parser.getName())){
newses.add(news);
news = null;
}
break;
}
event = parser.next();
}
return newses;
}








服务器端
Servlet:
List videos = service.getLastNews();
request.setAttribute("videos", videos);
request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response);

public List getLastNews(){
List newes = new ArrayList();
newes.add(new News(90, "喜羊羊与灰太狼全集", 78));
newes.add(new News(10, "实拍舰载直升东海救援演习", 28));
newes.add(new News(56, "喀麦隆VS荷兰", 70));
return newes;
}


JSP:



${video.title} - 锐客网
${video.timelength}



    推荐阅读