로그인

검색

JAVA/Android
2013.08.06 01:06

XML 파싱하기

MoA
조회 수 15101 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 게시글 수정 내역 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 게시글 수정 내역 댓글로 가기 인쇄
기상청의 xml파일을 다운받아서 파싱하는 코드이다.
(http://www.kma.go.kr/weather/forecast/mid-term-xml.jsp?stnId=109)

기상청의 xml파일 중 최대 온도에 해당하는 tmx 노드를 읽어온다.

MainActivity.java

package test.day08.xmlparser;

import java.io.BufferedReader;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
 
 //결과값을 출력할 EditText
 EditText editText;
 String xml; //다운로드된 xml문서
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        editText = (EditText)findViewById(R.id.editText);
        
    }
    //버튼을 눌렀을때 실행되는 메소드 
    public void down(View v){
     StringBuffer sBuffer = new StringBuffer();
     try{
      String urlAddr = " http://www.kma.go.kr/weather/forecast/mid-term-xml.jsp?stnId=109 ";
      //String urlAddr = "http://naver.com";
      URL url = new URL(urlAddr);
      HttpURLConnection conn = (HttpURLConnection)url.openConnection();
      if(conn != null){
       conn.setConnectTimeout(20000);
       conn.setUseCaches(false);
       if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
        //서버에서 읽어오기 위한 스트림 객체
        InputStreamReader isr = new InputStreamReader(conn.getInputStream());
        //줄단위로 읽어오기 위해 BufferReader로 감싼다.
        BufferedReader br = new BufferedReader(isr);
        //반복문 돌면서읽어오기
        while(true){
         String line = br.readLine();
         if(line==null){
          break;
         }
         sBuffer.append(line);
        }
        br.close();
        conn.disconnect();
       }
      }
      //결과값 출력해보기
      //editText.setText(sBuffer.toString());
      xml = sBuffer.toString(); //결과값 변수에 담기
     }catch (Exception e) {
   // TODO: handle exception
      Log.e("다운로드 중 에러 발생",e.getMessage());
      
  }
     parse();
     
    }
    
    //xml파싱하는 메소드
    public void parse(){
     try{
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder documentBuilder = factory.newDocumentBuilder();
      //xml을 InputStream형태로 변환
      InputStream is = new ByteArrayInputStream(xml.getBytes());
      //document와 element 는 w3c dom에 있는것을 임포트 한다.
      Document doc = documentBuilder.parse(is);
      Element element = doc.getDocumentElement();
      //읽어올 태그명 정하기
      NodeList items = element.getElementsByTagName("tmx");
      //읽어온 자료의 수
      int n = items.getLength();
      //자료를 누적시킬 stringBuffer 객체
      StringBuffer sBuffer = new StringBuffer();
      //반복문을 돌면서 모든 데이터 읽어오기
      for(int i=0 ; i < n ; i++){
       //읽어온 자료에서 알고 싶은 문자열의 인덱스 번호를 전달한다.
       Node item = items.item(i);
       Node text = item.getFirstChild();
       //해당 노드에서 문자열 읽어오기
       String itemValue = text.getNodeValue();
       sBuffer.append("최대온도:"+itemValue+"rn");
       
      }
      //읽어온 문자열 출력해보기
      editText.setText(sBuffer.toString());
      
     }catch (Exception e) {
   // TODO: handle exception
      Log.e("파싱 중 에러 발생", e.getMessage());
  }
    }
}


main.xml


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

    <Button android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="다운로드"
    android:onClick="down"  />
    <EditText android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:editable="false"
    android:id="@+id/editText"
    android:gravity="top"/>
</LinearLayout>


AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="test.day08.xmlparser"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
 <uses-permission android:name="android.permission.INTERNET"/>
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

http://blog.naver.com/khs7515?Redirect=Log&logNo=20155584927

?

  1. Programming 게시판 관련

    Date2014.11.01 CategoryTool/etc ByMoA Views94072
    read more
  2. 고양이 움직이기

    Date2013.11.08 CategoryPython ByMoA Views10922
    Read More
  3. CSS, 자바스크립트 강좌

    Date2013.11.05 CategorySite ByMoA Views10384
    Read More
  4. 슬라이더 컨트롤에 툴팁 삽입 (동적 툴팁)

    Date2013.10.28 CategoryAPI/MFC ByMoA Views11397
    Read More
  5. 태스크 대화상자 (Task Dialog)

    Date2013.10.22 CategoryAPI/MFC ByMoA Views11011
    Read More
  6. 프린터 출력하기

    Date2013.10.16 CategoryAPI/MFC ByMoA Views14994
    Read More
  7. Flash CS5 and Version Control

    Date2013.10.11 CategoryTool/etc ByMoA Views18548
    Read More
  8. AS3 Code Library

    Date2013.10.11 CategoryLibrary ByMoA Views18111
    Read More
  9. 영상 처리 관련 블로그

    Date2013.09.29 CategorySite ByMoA Views10416
    Read More
  10. [S/W 공학] 월-인원(man-month), LOC

    Date2013.09.23 CategoryTool/etc ByMoA Views19010
    Read More
  11. 졸업작품 및 각종 과제물 프로그램은 어떻게 만들어야 하나? (윈도우즈 응용프로그램)

    Date2013.09.10 CategorySite ByMoA Views11118
    Read More
  12. UpdateDialogControls

    Date2013.09.05 CategoryAPI/MFC ByMoA Views19527
    Read More
  13. MFC에서 생성,사용되는 파일 확장자

    Date2013.08.30 CategoryAPI/MFC ByMoA Views10862
    Read More
  14. 로그 클래스 및 업데이터

    Date2013.08.30 CategoryAPI/MFC ByMoA Views16356
    Read More
  15. 검색엔진 개발자 그룹

    Date2013.08.30 CategorySite ByMoA Views9904
    Read More
  16. CFile을 이용한 저장/불러오기

    Date2013.08.27 CategoryAPI/MFC ByMoA Views11930
    Read More
  17. DLL 생성 시 주의

    Date2013.08.22 CategoryAPI/MFC ByMoA Views13303
    Read More
  18. C++11 A cheat sheet

    Date2013.08.21 CategoryC/C++ ByMoA Views18027
    Read More
  19. 앱 디자인의 발견 - 메모 서비스를 생각하다

    Date2013.08.17 CategoryTool/etc ByMoA Views10326
    Read More
  20. 리스트 컨트롤에 체크박스 추가

    Date2013.08.14 CategoryAPI/MFC ByMoA Views12499
    Read More
  21. XML 파싱하기

    Date2013.08.06 CategoryJAVA/Android ByMoA Views15101
    Read More
Board Pagination Prev 1 ... 5 6 7 8 9 10 11 12 13 14 ... 17 Next
/ 17