본문 바로가기
옛날옛적

구글 오픈 API를 이용한 실시간 지역별 날씨 (XML 파싱하기...)

by Empering 2012. 7. 25.
반응형

예전에 자바공부를 할적에 구글 오픈 API를 이용해서 

날씨 정보를 가져오는 예제를 구현했던 적이있다. 

오늘은 그 생각이나서 혼자 책보고 인터넷보고 하면서

여기저기 긁고 모아서 작성해보았다.

 

xml정보를 가져오기위해서는 xml이 어떻게 생겼는지 한번 살펴볼 필요가 있다..

 

** 구글에서 제공하는 xml



<?xml version="1.0" encoding="UTF-8"?>
<xml_api_reply version="1">
   <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
      <forecast_information>
         <city data="seoul" />
         <postal_code data="seoul" />
         <latitude_e6 data="" />
         <longitude_e6 data="" />
         <forecast_date data="2012-03-19" />
         <current_date_time data="1970-01-01 00:00:00 +0000" />
         <unit_system data="SI" />
      </forecast_information>
      <current_conditions>
         <condition data="맑음" />
         <temp_f data="32" />
         <temp_c data="0" />
         <humidity data="습도: 25%" />
         <icon data="/ig/images/weather/sunny.gif" />
         <wind_condition data="바람: 북서풍, 13 km/h" />
      </current_conditions>
      <forecast_conditions>
         <day_of_week data="월" />
         <low data="0" />
         <high data="8" />
         <icon data="/ig/images/weather/mostly_sunny.gif" />
         <condition data="구름 조금" />
      </forecast_conditions>
      <forecast_conditions>
         <day_of_week data="화" />
         <low data="0" />
         <high data="9" />
         <icon data="/ig/images/weather/mostly_sunny.gif" />
         <condition data="대체로 맑음" />
      </forecast_conditions>
      <forecast_conditions>
         <day_of_week data="수" />
         <low data="2" />
         <high data="10" />
         <icon data="/ig/images/weather/mostly_sunny.gif" />
         <condition data="대체로 맑음" />
      </forecast_conditions>
      <forecast_conditions>
         <day_of_week data="목" />
         <low data="4" />
         <high data="10" />
         <icon data="/ig/images/weather/cloudy.gif" />
         <condition data="흐림" />
      </forecast_conditions>
   </weather>
</xml_api_reply>

 

많은 정보를 담고 있지만 우리가 필요한건 현재의 날씨이기 때문에

중간에 있는 <current_conditions> 내의 정보만 있으면 된다

 

<current_conditions> 안의 정보를 보면 자식노드들에 data 라는 속성에

우리가 원하는 값을 가지고 있는 것을 볼수있다

 

따라서 xml_api_reply -> weather -> current_conditions의 자식들의 속성 값을 가져오면

원하는 데이터를 다 가지고 오는 것이다

 

** 데이터를 가져오기 위한 코딩

using System.Xml;
using System.IO;
using System.Text;
using System.Net;


public partial class XMLTest_Test05 : System.Web.UI.Page
{
    String city = "seoul";
    String url = "http://www.google.co.kr";

 

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request["city"] != null)
                city = Request["city"];


            WebRequest req = WebRequest.Create(url + "/ig/api?weather=" + city);

            // http://www.google.co.kr/ig/api?weather=도시명 : 구글에서 날씨정보를 xml로 제공한다.


            StreamReader reader

                 = new StreamReader(req.GetResponse().GetResponseStream(), Encoding.Default);

            // 해당 주소로 Request를 보내고(req), req에서 Response를 StreamReader로 읽는다

 

            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            // StreamReader 로 한번 감싸지 않으면 구글에서 제공하는 xml의 인코딩 설정 때문에 에러가 남

 

            XmlNode currentNode = doc.SelectSingleNode("xml_api_reply/weather/current_conditions");

            // 현재의 날씨를 가지고 있는 노드를 선택한다

 

            string condition = currentNode.SelectSingleNode("condition").Attributes["data"].Value;
            string temp_c = currentNode.SelectSingleNode("temp_c").Attributes["data"].Value;
            string humidity = currentNode.SelectSingleNode("humidity").Attributes["data"].Value;
            string wind_condition = currentNode.SelectSingleNode("wind_condition").Attributes["data"].Value;
            String icon = url + currentNode.SelectSingleNode("icon").Attributes["data"].Value;

            // 구글에서 제공해준 xml 을 가지고 파싱하는 과정

            // 원하는 데이터를 다 가지고 왔기때문에 나머지 처리는 하고 싶은데로 해주기만 하면 된다

 

            DropDownList1.SelectedValue = city;
            this.icon.ImageUrl = icon;
            con.Text =

               "현재날씨 : " + condition + " " + temp_c + " ℃<br/>" + humidity + " " + wind_condition;
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        city = DropDownList1.SelectedItem.Value;
        Response.Redirect("XMLTest05.aspx?city=" + city);
    }
}

** 실행결과

 

반응형

'옛날옛적' 카테고리의 다른 글

Javascript jQuery dialog 제어하기  (0) 2012.07.25

댓글