Android 从网络下载xml文件并进行解析

来源:互联网 发布:手机淘宝多图变大代码 编辑:程序博客网 时间:2024/04/26 00:21
  1. public List<Contact> getContactAll() throws Exception {  
  2.         List<Contact> contacts = null;  
  3.         String Parth = "http://192.168.1.103:8080/myweb/list.xml";  
  4.         URL url = new URL(Parth);  
  5.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  6.         conn.setConnectTimeout(3000);  
  7.         conn.setRequestMethod("GET");  
  8.         if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {  
  9.             InputStream is = conn.getInputStream();  
  10.             // 这里获取数据直接放在XmlPullParser里面解析  
  11.             contacts = xmlParser(is);  
  12.             return contacts;  
  13.         } else {  
  14.             return null;  
  15.         }  
  16.     }  
  17.   
  18.     private List<Contact> xmlParser(InputStream is) throws Exception {  
  19.         List<Contact> contacts = null;  
  20.         Contact contact = null;  
  21.         XmlPullParser parser = Xml.newPullParser();  
  22.         parser.setInput(is, "UTF-8");  
  23.         int eventType = parser.getEventType();  
  24.         while ((eventType = parser.next()) != XmlPullParser.END_DOCUMENT) {  
  25.             switch (eventType) {  
  26.             case XmlPullParser.START_TAG:  
  27.                 if (parser.getName().equals("contacts")) {  
  28.                     contacts = new ArrayList<Contact>();  
  29.                 } else if (parser.getName().equals("contact")) {  
  30.                     contact = new Contact();  
  31.                     contact.setId(Integer.valueOf(parser.getAttributeValue(0)));  
  32.                 } else if (parser.getName().equals("name")) {  
  33.                     contact.setName(parser.nextText());  
  34.                 } else if (parser.getName().equals("image")) {  
  35.                     contact.setImage(parser.getAttributeValue(0));  
  36.                 }  
  37.                 break;  
  38.   
  39.             case XmlPullParser.END_TAG:  
  40.                 if (parser.getName().equals("contact")) {  
  41.                     contacts.add(contact);  
  42.                 }  
  43.                 break;  
  44.             }  
  45.         }  
  46.         return contacts;  
  47.     }  
0 0
原创粉丝点击