一、首先得到服务器端的xml文件
String path = "http://10.0.2.2:9999/XMLServer/video.xml";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(8 * 1000);
conn.setRequestMethod("GET");
InputStream is = conn.getInputStream();
byte[] data = StreamTools.readInput(is);
StreamTools代码:
public class StreamTools {
public static byte[] readInput(InputStream is) throws Exception {
byte[] buffer = new byte[is.available()];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = is.read(buffer)) != -1) {
bos.write(buffer,0,len);
}
bos.close();
return bos.toByteArray();
}
}
二、将得到的xml文件进行解析
/**
* 解析服务器返回来的xml数据
* @param content
* @return
* @throws Exception
*/
private static List
MyContentHandler代码:
public class MyContentHandler extends DefaultHandler {
private List videoList;
private Video video;
private String tagName;
public MyContentHandler() {
}
public MyContentHandler(List videoList) {
this.videoList = videoList;
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if("video".equals(localName)) {
video = new Video();
}
tagName = localName;
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if("video".equals(localName)) {
videoList.add(video);
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if("name".equals(tagName)) {
String name = new String(ch,start,length).trim();
if(StringTools.isNotEmpty(name)) {
video.setName(name);
}
} else if("time".equals(tagName)) {
String time = new String(ch,start,length).trim();
if(StringTools.isNotEmpty(time)) {
video.setTime(time);
}
}
}
}
三、最终得到解析出来的VO的List列表,在activity中用ListView显示出来
ListViewActivity代码:
public class ListViewActivity extends Activity {
private ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listtext);
list = (ListView)this.findViewById(R.id.list);
try {
List videolist = GetVideoService.getVideoList();
System.out.println("--------------"+videolist);
List