본문 바로가기
프로그래밍

[C#]기상청 날씨 데이터 XML 연동하기

by minimax95 2020. 7. 15.

이번 포스팅에서는 이전 포스팅에서 만든 구글맵 지도 애플리케이션 하단에 기상청 날씨 데이터 XML을 출력하는 기능을 추가해 보겠습니다.

 

이전 포스팅에 기상청 날씨 데이터를 출력하기 위해서 UI에 StatusStrip을 추가해 주고 두 개의 Label을 만들어 주었습니다.

기상청에서 날씨 데이터 XML 연동을 위해서 아래의 URL을 선언해 주어야 합니다.

다음으로 필요한 멤버는 기상정보를 저장할 Dictionary입니다. Dictionary<string, string> 타입으로 아래와 같이 선언해 줍니다.

Dictionary<string, string> DicWeather = new Dictionary<string, string>( );

 

그리고 기상정보를 2초마다 가져오는 일을 수행할 스레드와 toolStripStatusLabel에 데이터를 Display 해 주는 델리게이트를 선언해 주겠습니다.

Thread WeatherChkThread = null;
delegate void OnXmlDelegate(string k, string v);
OnXmlDelegate OXD = null;

 

나머지는 실제 일을 수행하는 함수들을 구현할 차례입니다.

스레드 함수에서는 아래와 같이 XmlDocument와 XmlNode 클래스를 이용하여 기상정보를 파싱하여 위에서 선언한 DicWeather에 저장하는 기능을 구현합니다.

private void GetWeather()
{

    XmlDocument xmlDocument = new XmlDocument();

    xmlDocument.Load(WeatherURL);

    XmlNode xmlNode = xmlDocument.DocumentElement;

    foreach (XmlNode xn in xmlNode.FirstChild.ChildNodes)
    {

        string strDataKey = String.Format("{0} / {1} / {2}", xn.InnerText, 

                                                      xn.Attributes["desc"].Value, xn.Attributes["ta"].Value);

        string strDataValue = "http://www.weather.go.kr/weather/forecast/mid-term_01.jsp";

        DicWeather.Add(strDataKey, strDataValue);

    }

}

 

델리게이트 함수는 아래와 같이 구현해 줍니다.

private void OnXmlRun(string key, string value)
{

    this.toolStripStatusLavbel2.Text = key;

    this.toolStripStatusLavbel2.ToolTipText = value;

}

 

Display 함수는 아래와 같습니다.

private void DisplayWeather()
{

    while (true)
    {

        foreach (KeyValuePair<string, string> news in DicWeather)
        {

            Invoke(OXD, news.Key, news.Value);

            Thread.Sleep(2000);

        }

    }

}

 

이제 Form1_Load 이벤트 처리기에서 델리게이트 객체를 생성해 주고 스레드를 시작하는 코드를 추가해 주겠습니다.

끝으로 프로그램 종료 시 FormClosing 이벤트 핸들러를 이용하여 스레드를 중단시키고 프로그램이 종료되도록 이벤트 핸들러를 등록해주겠습니다.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{

    if(WeatherChkThread != null) 

        WeatherChkThread.Abort( );

}

 

이제 솔루션을 빌드하여 실행해 보겠습니다.

우리가 추가한 기상청 날씨가 지도 하단에 표시되는 것을 확인할 수 있습니다.

감사합니다.

댓글