개발

자바로 xml 파싱하기

에드몽단테스 2009. 5. 18. 23:24

자주 사용하는 것임에도 불구하고 자꾸 잊어버린다.

그래서 간단한 xml 을 예제로서 적어본다.

 

아래 xml은 구글에서 제공하는 비공식(2009년 5월) 날씨 API이다.

지역은 대전.

 

<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="Daejeon"/>
<postal_code data="Daejeon"/>
<latitude_e6 data=""/>
<longitude_e6 data=""/>
<forecast_date data="2009-05-18"/>
<current_date_time data="2009-05-18 12:00:00 +0000"/>
<unit_system data="SI"/>
</forecast_information>
<current_conditions>
<condition data="맑음"/>
<temp_f data="63"/>
<temp_c data="17"/>
<humidity data="습도: 25%"/>
<icon data="/ig/images/weather/sunny.gif"/>
<wind_condition data="바람: 남풍, 10 km/h"/>
</current_conditions>
<forecast_conditions>
<day_of_week data="월"/>
<low data="10"/>
<high data="17"/>
<icon data="/ig/images/weather/mostly_sunny.gif"/>
<condition data="구름 조금"/>
</forecast_conditions>
<forecast_conditions>
<day_of_week data="화"/>
<low data="11"/>
<high data="25"/>
<icon data="/ig/images/weather/mostly_sunny.gif"/>
<condition data="대체로 맑음"/>
</forecast_conditions>
<forecast_conditions>
<day_of_week data="수"/>
<low data="13"/>
<high data="29"/>
<icon data="/ig/images/weather/mostly_sunny.gif"/>
<condition data="대체로 맑음"/>
</forecast_conditions>
<forecast_conditions>
<day_of_week data="목"/>
<low data="14"/>
<high data="22"/>
<icon data="/ig/images/weather/rain.gif"/>
<condition data="비"/>
</forecast_conditions>
</weather>
</xml_api_reply>

 

먼저 xml 파싱을 위한 패키지를 import 한다.

 

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

 

public class Main{
    private DocumentBuilder docBuilder;
    private String xmlData;
    private Document doc;

    public Main throws ParserConfigurationException, MalformedURLException, IOException, AXException{
        docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

        URL url = new URL("http://www.google.co.kr/ig/api?weather=Daejeon");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();

        byte[] bytes = new byte[4096];
        InputStream in = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while(true){
            int red = in.read(bytes);
            if(red < 0)
                break;
            baos.write(bytes, 0, red);
        }
        xmlData = baos.toString("euc-kr");  // 구글 날씨 API 는 현재 euc-kr 이다.
        baos.close();
        in.close();
        doc = docBuilder.parse(new InputSource(new StringReader(xmlData)));
        //System.out.println(xmlData);

        // 여기까지 진행이 되면 xml 파싱은 끝이 나며 doc에는 DOM 형태의 문서 구조를 갖는다.

        // 이제 DOM 을 파싱해보자.

 

        Element el = (Element)doc.getElementsByTagName("current_conditions").item(0);

        // 여기서 el 은 current_conditions 의 첫번째 노드 정보를 갖는다.

        // 이노드의 날씨 정보를 가져오자.

 

        String condition = ((Element)el.getElementsByTagName("condition").item(0)).getAttribute("data");

        // 첫번째 current_conditions 노드 정보중 첫번째 condition 노드의 "data" 속성을 불러온다.

        // 끝.
    }

}

 

에러처리라든지 기타 몇몇가지 처리가 되지 않았기때문에 정상적으로 동작하지는 않겠지만,

xml 파싱 및 돔구조의 기본 파싱은 구현이 되어 있다.

이정도만 알아도 파싱은 충분할 듯. ㅋ

반응형