본문 바로가기

JAVA/Android

안드로이드 html,xml 파싱 예제 따라하기

- 인터넷에 있는 자료를 나의 App에 가져와서 데이터를 내 것 처럼 사용하는 기술이 파싱이라고 한다. 이 파싱을 이용하는 간단한 예제를 해보자.
- 네이버 html, xml 소스를 띄어보고 트윗 tag를 짤라서 화면에 출력하는 간단한 예제이다.

- Java 소스
public class Ex13_HTTPActivity extends Activity implements OnClickListener {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  Button xml = (Button) this.findViewById(R.id.xml);
  xml.setOnClickListener(this);
  Button html = (Button) this.findViewById(R.id.html);
  html.setOnClickListener(this);
  Button parse = (Button) this.findViewById(R.id.parse);
  parse.setOnClickListener(this);
 }

 @Override
 public void onClick(View arg0) {
  // TODO Auto-generated method stub
  TextView text1 = (TextView) this.findViewById(R.id.tv1);
  switch (arg0.getId()) {

  case R.id.html:
   String html = downloadURL("http://www.naver.com");
   text1.setText(html);
   break;
  case R.id.xml:
   // String name = "oisoo";
   // int count = 2;
   String url1 = "http://www.naver.com";
   // ? 뒤에는 매개변수 & 추가적인 정보
   String xml1 = downloadURL(url1);
   text1.setText(xml1);

   break;
  case R.id.parse:

   String url = "http://twitter.com/statuses/user_timeline.xml?screen_name=oisoo&count=5";
   // ? 뒤에는 매개변수 & 추가적인 정보
   String xml = downloadURL(url);
   parseXML(xml);
   break;

  }

 }

 void parseXML(String xml) {
  int itemtype = 0;
  String itemText = "";

  try {
   XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
   XmlPullParser parser = factory.newPullParser();
   parser.setInput(new StringReader(xml));
   // 여기까지 의미있는부분을 짤라준다.
   int eventType = parser.getEventType();
   while (eventType != XmlPullParser.END_DOCUMENT) {
    switch (eventType) {
    case XmlPullParser.START_DOCUMENT:
     break;
    case XmlPullParser.END_DOCUMENT:
     break;
    case XmlPullParser.START_TAG:
     if (parser.getName().equals("text")) {
      itemtype = 1;
     }

    case XmlPullParser.END_TAG:
     break;
    case XmlPullParser.TEXT:
     if (itemtype == 1) {
      itemText = itemText + parser.getText() + "\n";
      itemtype = 0;
     }
     break;
    }
    eventType = parser.next();
   }
  } catch (Exception e) {
   ;
  }
  TextView text1 = (TextView) this.findViewById(R.id.tv1);
  text1.setText(itemText);

 }

 String downloadURL(String addr) {
  String doc = "";
  try {
   URL url = new URL(addr);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();

   if (conn != null) {
    conn.setConnectTimeout(10000);
    conn.setUseCaches(false);
    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { // 연결이
                   // 완성이됫다
     BufferedReader br = new BufferedReader(
       new InputStreamReader(conn.getInputStream()));
     for (;;) {
      String line = br.readLine();
      if (line == null)
       break;
      doc = doc + line + "\n";
     }
     br.close();
    }
    // conn.disconnect();
   }
  } catch (Exception ex) {
   ;
  }

  return doc;

 }

}

-xml 소스
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/html"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="HTML" />

        <Button
            android:id="@+id/xml"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="XML" />

        <Button
            android:id="@+id/parse"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Parse XML" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >

        <TextView
            android:id="@+id/tv1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

-실행 화면