首页 > 代码库 > Pull解析XML

Pull解析XML

一.xml数据

<apps>
<app>
<id>1</id>
<name>Google Maps</name>
<version>1.0</version>
</app>
<app>
<id>2</id>
<name>Chrome</name>
<version>2.1</version>
</app>
<app>
<id>3</id>
<name>Google Play</name>
<version>2.3</version>
</app>
</apps>

 

二.关键方法

public class MainActivity extends Activity {

    TextView content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        content = (TextView)findViewById(R.id.content);

    }

    protected void myClick(View v){
        if(v.getId() == R.id.btn){
            getXml();
        }
    }


    private void getXml(){

        OkHttpClient http = new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://192.168.2.100:8001/a.xml")
                .build();

        Call call = http.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                parseXmlPull(response.body().string());
            }
        });
    }

    private void parseXmlPull(String xmldata){
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(new StringReader(xmldata));
            int eventType = parser.getEventType();

            String id = "";
            String name = "";
            String version = "";

            while (eventType != XmlPullParser.END_DOCUMENT){
                String nodeName = parser.getName();
                switch (eventType){
                    // 开始解析节点
                    case XmlPullParser.START_TAG:
                        if( "id".equals(nodeName) ){
                            id = parser.nextText();
                        }else if("name".equals(nodeName)){
                            name = parser.nextText();
                        }
                        else if("version".equals(nodeName)){
                            version = parser.nextText();
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if("app".equals(nodeName)){
                            Log.e("id", id);
                            Log.e("name", name);
                            Log.e("version", version);
                        }
                        break;
                    default:
                        break;
                }
                eventType = parser.next();
            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

Pull解析XML