로그인

검색

JAVA/Android
2013.08.06 01:06

XML 파싱하기

MoA
조회 수 8945 추천 수 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

?

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
공지 Tool/etc Programming 게시판 관련 2 MoA 2014.11.01 15455
98 Site 10 Useful/Fun/Weird Github Repos You Have to Play Around With OBG 2023.12.28 2801
97 Tool/etc What does the last “-” (hyphen) mean in options of `bash`? OBG 2021.04.29 2797
96 C/C++ C Runtime 환경의 메모리 릭 잡는 방법 (Memory leak) Naya 2012.08.02 2795
95 API/MFC VC++6.0 에서 VC++ 2005로 변환할 경우 형변환 경고 대응방법 MoA 2013.07.28 2790
94 Python [첫게임 만들기] 2. 배경 그리기, Bunny 움직이게 하기 file MoA 2013.11.21 2788
93 Tool/etc How to stop programmers to copy the code from GitHub when they leave the company? OBG 2024.01.02 2788
92 C/C++ 코드 실행 시간 계산 Naya 2012.09.27 2781
91 API/MFC char*, String, CString MoA 2013.07.28 2777
90 Database What's the difference between comma separated joins and join on syntax in MySQL? OBG 2022.06.09 2777
89 Tool/etc 소스 코드 버전 관리 툴 설치 Naya 2012.08.02 2776
88 API/MFC DLL 이란 MoA 2013.07.28 2770
87 Site 검색엔진 개발자 그룹 MoA 2013.08.30 2758
86 Site GOF 디자인패턴 정리 MoA 2013.07.28 2753
85 Web 카카오톡 웹버전 만들기 OBG 2022.11.09 2751
84 JAVA/Android 안드로이드 프로세스 확인 MoA 2013.04.09 2739
83 Tool/etc Design Patterns Quick Reference MoA 2013.07.28 2727
82 Site IT 세미나 유튜브 동영상 Naya 2012.09.10 2689
81 Site 윈도우 8 앱 개발 동영상 강의 Naya 2012.09.10 2679
80 API/MFC Legacy MFC 어플리케이션을 MFC feature pack으로 포팅 MoA 2013.07.30 2672
79 Tool/etc How To Set Up Multi-Factor Authentication for SSH on Ubuntu 20.04 OBG 2023.01.17 2664
Board Pagination Prev 1 ... 6 7 8 9 10 11 12 13 14 15 Next
/ 15