Android开发之Pull解析XML文件

// HTTP请求本地服务器
private void sendRequestWithOkHttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("http://192.168.0.104:82/get_data.xml").build();
                    Response response = client.newCall (request).execute();
                    String  ResponseData = response.body().string();
                    parseXMLWithPull(ResponseData);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

private void parseXMLWithPull(String xmlData){
        try{
            //获取xmlPullParserFactory实例,借助实例获取xmlPullParser对象
            XmlPullParserFactory  factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            //setInput方法传入服务器返回的xmlData
            xmlPullParser.setInput(new StringReader(xmlData));
            //getEventType得到当前的解析事件
            int eventType = xmlPullParser.getEventType();
            String id ="";
            String name = "";
            String version = "";
            //eventType !=  END_DOCUMENT 解析工作未完成
            while(eventType != XmlPullParser.END_DOCUMENT){
                //getName 得到当前节点名字
                String  nodeName = xmlPullParser.getName();
                switch (eventType){
                    case XmlPullParser.START_TAG:{
                        if("id".equals(nodeName))
                            //调用nextText获取节点具体内容
                            id = xmlPullParser.nextText();
                        else if("name".equals(nodeName))
                            name = xmlPullParser.nextText();
                        else if("version".equals(nodeName))
                            version = xmlPullParser.nextText();
                        break;
                    }

                    case XmlPullParser.END_TAG:{
                        //解析完一个app节点就打印
                        if("app".equals(nodeName))
                        {
                            Log.d("MainActivity","id is " + id);
                            Log.d("MainActivity","name is " + name);
                            Log.d("MainActivity","version is " + version);

                        }
                        break;
                    }
                    default:break;
                }
                eventType = xmlPullParser.next();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


需要注意使用真机调试时,需用手机和电脑接入同一个WiFi,然后对电脑局域网中IP地址进行HTTP请求。

你可能感兴趣的:(Android)