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

public List<Contact> getContactAll() throws Exception {  
        List<Contact> contacts = null;  
        String Parth = "http://192.168.1.103:8080/myweb/list.xml";  
        URL url = new URL(Parth);  
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
        conn.setConnectTimeout(3000);  
        conn.setRequestMethod("GET");  
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {  
            InputStream is = conn.getInputStream();  
            // 这里获取数据直接放在XmlPullParser里面解析  
            contacts = xmlParser(is);  
            return contacts;  
        } else {  
            return null;  
        }  
    }  

    private List<Contact> xmlParser(InputStream is) throws Exception {  
        List<Contact> contacts = null;  
        Contact contact = null;  
        XmlPullParser parser = Xml.newPullParser();  
        parser.setInput(is, "UTF-8");  
        int eventType = parser.getEventType();  
        while ((eventType = parser.next()) != XmlPullParser.END_DOCUMENT) {  
            switch (eventType) {  
            case XmlPullParser.START_TAG:  
                if (parser.getName().equals("contacts")) {  
                    contacts = new ArrayList<Contact>();  
                } else if (parser.getName().equals("contact")) {  
                    contact = new Contact();  
                    contact.setId(Integer.valueOf(parser.getAttributeValue(0)));  
                } else if (parser.getName().equals("name")) {  
                    contact.setName(parser.nextText());  
                } else if (parser.getName().equals("image")) {  
                    contact.setImage(parser.getAttributeValue(0));  
                }  
                break;  

            case XmlPullParser.END_TAG:  
                if (parser.getName().equals("contact")) {  
                    contacts.add(contact);  
                }  
                break;  
            }  
        }  
        return contacts;  
    }  

说点什么

avatar
  Subscribe  
提醒