1. 程式人生 > >Android解析xml檔案

Android解析xml檔案

public void pullxml(View v){
        //獲取資原始檔並轉化為輸入流
        try {
            InputStream is=ClassLoader.getSystemResourceAsStream("hey.xml");
            //獲取xml解析器物件
            XmlPullParser xmlPullParser= Xml.newPullParser();
            //獲取輸入流,並設定編碼格式
            xmlPullParser.setInput(is,"utf-8");
            //獲取節點型別
            int type=xmlPullParser.getEventType();
            while (type!= XmlPullParser.END_DOCUMENT){//如果檔案不是結束符號的話
                switch (type){
                    case XmlPullParser.START_TAG :
                        if(xmlPullParser.getName().equals("weather")){
                            cityList=new ArrayList<>();
                        }
                        else if(xmlPullParser.getName().equals("city")){
                            city=new City();
                        }
                        else if(xmlPullParser.getName().equals("name")){
                            city.setName(xmlPullParser.nextText());
                        }
                        else if(xmlPullParser.getName().equals("temperature")){
                            city.setTemperature(xmlPullParser.nextText());
                        }
                        else if(xmlPullParser.getName().equals("pm25")){
                            city.setPm25(xmlPullParser.nextText());
                        }
                        else if(xmlPullParser.getName().equals("forecast")){
                            city.setForecast(xmlPullParser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG :
                        if(xmlPullParser.getName().equals("city"))
                           cityList.add(city);
                        break;
                }
                type=xmlPullParser.next();
            }
            for (City cit:cityList) {
                System.out.print(cit.toString());
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }