2025년, 코딩은 선택이 아닌 필수!

2025년 모든 학교에서 코딩이 시작 됩니다. 먼저 준비하는 사람만이 기술을 선도해 갑니다~

강의자료/C#

[C#] 공공데이터 API 를 이용한 버스 도착정보 조회

원당컴1 2021. 2. 25. 12:33
목표

- 공공데이터 API를 활용하는 방법 알아보기

- XML 데이터를 파싱하는 방법 알아 보기

 

준비

- www.data.go.kr  에서 회원가입 후 공공데이터 오픈API 활용신청

- 데이터목록에서 인천 버스로 검색 하여 다음과 같은 4가지 서비스를 활용신청

 

 

 

폼구성

위와 같이 폼을 두개 구성

[Form1]

- panel : 1개 Dock-Top

- label,textbox,button : 각각 1개씩 panel 위에 올림

- listview : Dock-Fill, View-Details, Columns 의 열 6개 추가 하여 위와 같이 버스번호/차량번호/현재위치/남은좌석/남은정거장/노선번호로 Text를 변경

 

[Form2]

- listview : Columns 에 열 3개를 추가하여 지역/정류소명,정류소아이디 로 Text 변경

- 버튼 2개 -선택/취소

 

 

작업순서

1) 정류소 조회 API를 이용하여 정류소명으로 정류소 아이디를 가져온다.

2) 버스도착정보 조회 API를 이용하여 정류소아이디로 버스도착 정보를 가져온다.

3) 버스노선조회 API를 이용하여 버스도착정보의 노선번호로 버스번호를 가져온다.

 

 

소스코드

[Form1] - 소스코드

 

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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
 
namespace JsonAPI
{
    public partial class Form1 : Form
    {
        
 
        String busStationID;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void getBusStationList()
        {
            throw new NotImplementedException();
        }
 
        private void btn_BusStationSearch_Click(object sender, EventArgs e)
        {
            Form2 frm = new Form2();
            try
            {
                frm.setBusStationName(txt_BusStationName.Text);
                frm.ShowDialog();
                busStationID = frm.getBusStationID();
                txt_BusStationName.Text = frm.getBusStationName();
                Console.WriteLine(busStationID);
                ArrivalInformation(busStationID);
            }
            finally
            {
                if (frm != null) frm.Dispose();
                //if (frm != null) ((IDisposable)frm).Dispose(); //폼을 해제하자
            }           
            
        }
 
        private void ArrivalInformation(string busStationID)
        {
            WebClient wc = null;
            XmlDocument doc = null;
            XmlNode root = null;
 
            wc = new WebClient() { Encoding = Encoding.UTF8 };
            doc = new XmlDocument();
            String stBusPlate="";
            String stLastBusStationName="";
            String stRemaindSeat="";
            String stRestStopCount="";
            String stRouteID="";
            String stBusNo = "";
            this.lv_BusState.Items.Clear();
 
            try
            {
                List<string> ltReturn = new List<string>();
                String xmlData = wc.DownloadString(new Uri("http://apis.data.go.kr/6280000/busArrivalService/getAllRouteBusArrivalList?serviceKey=" + 승인번호 + "&pageNo=1&numOfRows=10&bstopId=" + busStationID ));
                doc.LoadXml(xmlData);
                root = doc.SelectSingleNode("ServiceResult");
                XmlNode msgHeader = root.SelectSingleNode("msgHeader");
                if (msgHeader.SelectSingleNode("resultCode").InnerText != "0")
                {
                    return//정상으로 들어 오지 않았으면 빠져 나가자
                }
 
                XmlNodeList itemList = doc.GetElementsByTagName("itemList");
                foreach (XmlNode nowItem in itemList)
                {
                    if (nowItem["BUS_NUM_PLATE"!= null)
                    {
                        Console.WriteLine(nowItem["BUS_NUM_PLATE"].InnerText.ToString());
                        stBusPlate = nowItem["BUS_NUM_PLATE"].InnerText.ToString();
                    }
                    if (nowItem["LATEST_STOP_NAME"!= null)
                    {
                        Console.WriteLine(nowItem["LATEST_STOP_NAME"].InnerText.ToString());
                        stLastBusStationName = nowItem["LATEST_STOP_NAME"].InnerText.ToString();
                    }
                    if (nowItem["REMAIND_SEAT"!= null)
                    {
                        Console.WriteLine(nowItem["REMAIND_SEAT"].InnerText.ToString());
                        stRemaindSeat = nowItem["REMAIND_SEAT"].InnerText.ToString();
                    }
                    if (nowItem["REST_STOP_COUNT"!= null)
                    {
                        Console.WriteLine(nowItem["REST_STOP_COUNT"].InnerText.ToString());
                        stRestStopCount = nowItem["REST_STOP_COUNT"].InnerText.ToString();
                        // this.lv_BusStation.Items.Add(new ListViewItem(new string[] { stPosition, stBusStationName, stBusStationID }));
                    }
                    if (nowItem["ROUTEID"!= null)
                    {
                        Console.WriteLine(nowItem["ROUTEID"].InnerText.ToString());
                        stRouteID = nowItem["ROUTEID"].InnerText.ToString();
                        stBusNo = getBusNo(stRouteID); //노선번호로 버스번호를 가져오자
                        this.lv_BusState.Items.Add(new ListViewItem(new string[] { stBusNo, stBusPlate, stLastBusStationName, stRemaindSeat, stRestStopCount, stRouteID }));
                    }
 
                }
            }
            catch (Exception e)
            {
                return;
            }
            finally
            {
                doc = null;
                root = null;
                wc.Dispose();
            }
 
            
        }
 
        private String getBusNo(String stRouteID)
        {
            WebClient wc = null;
            XmlDocument doc = null;
            XmlNode root = null;
 
            wc = new WebClient() { Encoding = Encoding.UTF8 };
            doc = new XmlDocument();
            String stBusNo = "";
            try
            {
                List<string> ltReturn = new List<string>();
                String xmlData = wc.DownloadString(new Uri("http://apis.data.go.kr/6280000/busRouteService/getBusRouteId?serviceKey=" + 승인번호 + "&pageNo=1&numOfRows=10&routeId=" + stRouteID));
                doc.LoadXml(xmlData);
                root = doc.SelectSingleNode("ServiceResult");
                XmlNode msgHeader = root.SelectSingleNode("msgHeader");
                if (msgHeader.SelectSingleNode("resultCode").InnerText != "0")
                {
                    return ""//정상으로 들어 오지 않았으면 빠져 나가자
                }
 
                XmlNodeList itemList = doc.GetElementsByTagName("itemList");
                foreach (XmlNode nowItem in itemList)
                {
                    if (nowItem["ROUTENO"!= null)
                    {
                        Console.WriteLine(nowItem["ROUTENO"].InnerText.ToString());
                        return stBusNo = nowItem["ROUTENO"].InnerText.ToString();
                    }
                    
 
                }
            }
            catch (Exception e)
            {
                return "";
            }
            finally
            {
                doc = null;
                root = null;
                wc.Dispose();
            }
 
            return stBusNo;
        }
    }
}
 
cs

 

 

 

 

[Form2] - 소스코드

 

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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
 
namespace JsonAPI
{
    public partial class Form2 : Form
    {
        WebClient wc = null;
        XmlDocument doc = null;
        XmlNode root = null;
 
        public static String busStationName="";
        public static String busStationID="";
        public Form2()
        {
            InitializeComponent();
 
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            Close();
        }
 
        public void setBusStationName(String name)
        {
            busStationName = name;
        }
        public String getBusStationName()
        {
            return busStationName ;
        }
        public String getBusStationID()
        {
            return busStationID;
        }
 
        private void Form2_Load(object sender, EventArgs e)
        {
            getBusStaiontList(busStationName);
        }
 
        private void getBusStaiontList(string busStationName)
        {
            String stPosition = "";
            String stBusStationName = "";
            String stBusStationID = "";
            this.lv_BusStation.Items.Clear();
            wc = new WebClient() { Encoding = Encoding.UTF8 };
            doc = new XmlDocument();
            try
            {
                List<string> ltReturn = new List<string>();
                String xmlData = wc.DownloadString(new Uri("http://apis.data.go.kr/6280000/busStationService/getBusStationNmList?serviceKey=" + 승인번호 + "D&pageNo=1&numOfRows=10&bstopNm=" + busStationName ));
                doc.LoadXml(xmlData);
                root = doc.SelectSingleNode("ServiceResult");
                XmlNode msgHeader = root.SelectSingleNode("msgHeader");
                if (msgHeader.SelectSingleNode("resultCode").InnerText != "0" )
                {
                    return//정상으로 들어 오지 않았으면 빠져 나가자
                }
                
                XmlNodeList itemList = doc.GetElementsByTagName("itemList");
                foreach (XmlNode nowItem in itemList)
                {
                    if (nowItem["ADMINNM"!= null)
                    {
                        Console.WriteLine(nowItem["ADMINNM"].InnerText.ToString());
                        stPosition = nowItem["ADMINNM"].InnerText.ToString();
                    }
                    if (nowItem["BSTOPNM"!= null)
                    {
                        Console.WriteLine(nowItem["BSTOPNM"].InnerText.ToString());
                        stBusStationName = nowItem["BSTOPNM"].InnerText.ToString();
                    }
                    if (nowItem["BSTOPID"!= null)
                    {
                        Console.WriteLine(nowItem["BSTOPID"].InnerText.ToString());
                        stBusStationID = nowItem["BSTOPID"].InnerText.ToString();
                    }
                    if (nowItem["SHORT_BSTOPID"!= null)
                    {
                        Console.WriteLine(nowItem["SHORT_BSTOPID"].InnerText.ToString());
                        this.lv_BusStation.Items.Add(new ListViewItem(new string[] { stPosition, stBusStationName, stBusStationID }));
                    }
                    
                }
 
 
 
            }
            catch(Exception e)
            {
                return;
            }
            finally
            {
                doc = null;
                root = null;
                wc.Dispose();
            }
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            if(this.lv_BusStation.SelectedItems.Count>0)
            {
                int index = this.lv_BusStation.SelectedItems[0].Index;
                busStationID = this.lv_BusStation.Items[index].SubItems[2].Text;
                busStationName = this.lv_BusStation.Items[index].SubItems[1].Text;
                Close();
            }
        }
    }
}
 
cs

JsonAPI.zip
0.06MB

 

동작

 

정류소명을 입력하여 해당 정류소를 조회 하여 정류소의 아이디를 가져 온다.

정류소 아이디를 가져와서 버스 도착정보API를 사용하여 버스의 현재 위치와 남은정거장/남은좌석 정보를 가져온다.

버스노선을 이용하여 버스번호를 가져와서 현재 버스가 언제 도착할지 버스의 정보를 알려 준다.

 

활용

- 공공데이터를 분석하여 활용하여 편리한 프로그램을 만들어 볼 수가 있다.

- XML 파싱과 웹서비스와의 연동방법등을 살펴 봄으로 웹서비스와 연동에 활용될 수 있다.

 

 

=====================================================

이 자료는 학생들과 특강시간에 만들어 보는 프로젝트입니다.

=====================================================

 

오늘도 최선을 다하는 우리 학생들을 응원합니다.

인천 서구 검단신도시 원당컴퓨터학원

사업자 정보 표시
원당컴퓨터학원 | 기희경 | 인천 서구 당하동 1028-2 장원프라자 502호 | 사업자 등록번호 : 301-96-83080 | TEL : 032-565-5497 | Mail : icon001@naver.com | 통신판매신고번호 : 호 | 사이버몰의 이용약관 바로가기