메뉴 건너뛰기

OBG

Programming

JAVA/Android
2013.08.06 01:06

XML 파싱하기

MoA
조회 수 7062 추천 수 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 Views1709
    read more
  2. 고수가 절대 알려주지 않는 C/C++ 팁

    Date2011.09.23 CategoryC/C++ By너울 Views359
    Read More
  3. 검색엔진 개발자 그룹

    Date2013.08.30 CategorySite ByMoA Views283
    Read More
  4. 개발자를 위한 각 기업 오픈소스 공유 사이트 (주로 모바일)

    Date2012.08.02 CategorySite ByNaya Views683
    Read More
  5. 개발에 도움되는 사이트 (초보 개발자 꿀팁)

    Date2023.01.28 CategorySite ByOBG Views91
    Read More
  6. 강화학습 학습 관련 정리

    Date2022.08.10 CategoryDeeplearning ByOBG Views117
    Read More
  7. XML 파싱하기

    Date2013.08.06 CategoryJAVA/Android ByMoA Views7062
    Read More
  8. WTL 정리

    Date2013.12.22 CategoryAPI/MFC ByMoA Views947
    Read More
  9. Windows 10 앱 개발(UWP)

    Date2015.10.13 CategoryAPI/MFC ByMoA Views850
    Read More
  10. Win32 Socket Class

    Date2012.08.02 CategoryLibrary ByNaya Views926
    Read More
  11. Which Font is the default for MFC Dialog Controls

    Date2013.06.12 CategoryAPI/MFC ByMoA Views391
    Read More
  12. What's the difference between comma separated joins and join on syntax in MySQL?

    Date2022.06.09 CategoryDatabase ByOBG Views148
    Read More
  13. What to use instead of “addPreferencesFromResource” in a PreferenceActivity?

    Date2013.06.13 CategoryJAVA/Android ByMoA Views475
    Read More
  14. What does the last “-” (hyphen) mean in options of `bash`?

    Date2021.04.29 CategoryTool/etc ByOBG Views152
    Read More
  15. What does set -e mean in a bash script?

    Date2021.04.29 CategoryTool/etc ByOBG Views154
    Read More
  16. WaitForSingleObject와의 삽질..

    Date2013.07.28 CategoryAPI/MFC ByMoA Views429
    Read More
  17. Visual Studio Debug Tips

    Date2013.02.19 CategoryTool/etc ByMoA Views416
    Read More
  18. Visual C++ 시리얼 통신(RS-232) 강좌 (2)

    Date2013.07.28 CategoryAPI/MFC ByMoA Views4461
    Read More
  19. Visual C++ 시리얼 통신(RS-232) 강좌 (1)

    Date2013.07.28 CategoryAPI/MFC ByMoA Views6716
    Read More
  20. Video Preview and Frames Capture

    Date2013.07.28 CategoryGraphic ByMoA Views847
    Read More
  21. VC의 소스 파일, sln파일 관리

    Date2013.07.28 CategoryAPI/MFC ByMoA Views334
    Read More
Board Pagination Prev 1 ... 2 3 4 5 6 7 8 9 10 ... 15 Next
/ 15
위로