프로그래밍/안드로이드

안드로이드 XmlPullParser 사용 예제

가카리 2013. 12. 1. 22:48
반응형

  : 권한 필요 ( <uses-permission android:name="android.permission.INTERNET">

           - androidmanifest 파일에 추가 필요

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
///////////////////외부url연결시///////////////////
String data = editLoc.getText().toString();
 
//한글을 인코딩해서 인터넷으로 내보내기
data = URLEncoder.encode(data, "UTF-8");
 
String requestURL = "http://www.google.co.kr/ig/api?weather="+data;
URL url = new URL(requestURL);
 
InputStream is = url.openStream();
////////////////////////////////////////////////////
 
///////////////////내부xml파일이용시///////////////////
 InputStream is = getResources().openRawResource(R.raw.person);
/////////////////////////////////////////////////////////
 
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
      
     parser.setInput(is, "UTF-8");
     int eventType = parser.getEventType();
      
     while(eventType != XmlPullParser.END_DOCUMENT) {
       
      switch(eventType) {
       
      case XmlPullParser.START_TAG:
        
       String startTag = parser.getName();
        
       if(startTag.equals("item")) { search = new SearchData(); }
        
       //방법 1. 속성값일때 얻기
     p.setName(parser.getAttributeValue(0));
     p.setAge(parser.getAttributeValue(1));
     p.setAddress(parser.getAttributeValue(2));
 
       //방법 2. 태그값일때 얻기
       if(search != null) {
           if(startTag.equals("title")) {
                 String temp = parser.nextText();
                 temp=temp.replace("<b>", "");
                 temp=temp.replace("</b>", "");
                 search.setTitle(temp);
           }
           if(startTag.equals("link")) { search.setLink(parser.nextText()); }
           if(startTag.equals("description")) { search.setDescription(parser.nextText()); }
           if(startTag.equals("telephone")) { search.setTelephone(parser.nextText()); }
           if(startTag.equals("address")) { search.setAddress(parser.nextText()); }
           if(startTag.equals("mapx")) { search.setMapx(parser.nextText()); }
           if(startTag.equals("mapy")) { search.setMapy(parser.nextText()); }
       }
        
       break;
        
      case XmlPullParser.END_TAG:
        
       String endTag = parser.getName();
       if(endTag.equals("item")) { list.add(search); }
        
      }//end switch
       
      eventType = parser.next();
       
     }//end while
      
    }

 

출처 :  http://androphil.tistory.com/entry/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-XmlPullParser-%EC%82%AC%EC%9A%A9-%EC%98%88%EC%A0%9C