XML 파싱 ( DOM Parser ) ( AsyncTask 클래스 사용 )

프로그래밍/Android (Java)|2015. 10. 14. 10:43
반응형

참고 링크 

 

날씨 정보 RSS 서비스 페이지 (기사청) : http://www.kma.go.kr/weather/lifenindustry/sevice_rss.jsp 

날씨 정보 RSS (기사청 : 서울) http://www.kma.go.kr/weather/forecast/mid-term-xml.jsp?stnId=108 

공공데이터 포털 : 공공데이터 포털 기상청 Open API 사이트

 

샘플 URL : http://www.kma.go.kr/wid/queryDFS.jsp?gridx=61&gridy=125

 

 

예제) 기상청에서 제공하는 날씨정보 (xml) 를 파싱하여 출력하는 예제 

 

 [코드]

activity_xmlparsing_domexample.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onClick"
    android:text="click" />


<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:text="" />


</LinearLayout>

AndroidManifest.xml

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
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.xmlparsingdomexample"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <!-- 인터넷 접속 허용 -->
    <uses-permission android:name="android.permission.INTERNET"/>
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.example.xmlparsingdomexample.XMLParsingDOMExample"
            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>

XMLParsingDOMExample.java

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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.example.xmlparsingdomexample;

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 org.xml.sax.InputSource;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class XMLParsingDOMExample extends Activity {

    
    TextView textview;
    Document doc = null;
    LinearLayout layout = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xmlparsing_domexample);
        
        textview = (TextView) findViewById(R.id.textView1);
        
    }
    
    public void onClick(View view){
        GetXMLTask task = new GetXMLTask();
        task.execute("http://www.kma.go.kr/wid/queryDFS.jsp?gridx=61&gridy=125");
        
    }
    
    
    
    //private inner class extending AsyncTask
    private class GetXMLTask extends AsyncTask<String, Void, Document>{    
        
        @Override
        protected Document doInBackground(String... urls) {
            URL url;
            try {
                url = new URL(urls[0]);
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder(); //XML문서 빌더 객체를 생성
                doc = db.parse(new InputSource(url.openStream())); //XML문서를 파싱한다.
                doc.getDocumentElement().normalize();
                
            } catch (Exception e) {
                Toast.makeText(getBaseContext(), "Parsing Error", Toast.LENGTH_SHORT).show();
            }
            return doc;
        }
        
        @Override
        protected void onPostExecute(Document doc) {
            
            String s = "";
            //data태그가 있는 노드를 찾아서 리스트 형태로 만들어서 반환
            NodeList nodeList = doc.getElementsByTagName("data"); 
            //data 태그를 가지는 노드를 찾음, 계층적인 노드 구조를 반환
            
            for(int i = 0; i< nodeList.getLength(); i++){
                
                //날씨 데이터를 추출
                s += "" +i + ": 날씨 정보: ";
                Node node = nodeList.item(i); //data엘리먼트 노드
                Element fstElmnt = (Element) node;
                NodeList nameList  = fstElmnt.getElementsByTagName("temp");
                Element nameElement = (Element) nameList.item(0);
                nameList = nameElement.getChildNodes();
                s += "온도 = "+ ((Node) nameList.item(0)).getNodeValue() +" ,";
                
                
                NodeList websiteList = fstElmnt.getElementsByTagName("wfKor");
                //<wfKor>맑음</wfKor> =====> <wfKor> 태그의 첫번째 자식노드는 TextNode 이고 TextNode의 값은 맑음
                s += "날씨 = "+  websiteList.item(0).getChildNodes().item(0).getNodeValue() +"\n";
                
                
            }
            
            textview.setText(s);
            
            super.onPostExecute(doc);
        }
        
        
    }//end inner class - GetXMLTask     
}

 

 

xml 내용 일부.

 

 


 



[출처http://m.blog.naver.com/javaking75/140196029200


XMLParsingDOMExample.zip


반응형

댓글()