Weather

XML パース機能

xgawk が元々 xmlgawk と言われていたように、最初は gawk の XML パース機能拡張版として開発がスタートされました。 XML のような構造体は awk では扱いにくいとされていましたが、Expat による XML パース機能の搭載により大幅に扱いやすくなっています。

xgawk は well formated な XML しか扱えないため、ここでは天気予報の XML をパースさせて表示させています。 なお、XML はデフォルトでは UTF-8 ですが、他の文字コードも扱うことが可能になっています。

weather.awk

#! /usr/local/bin/xgawk -f

@load xml

BEGIN {
    # 各地の天気
    print_weather("さいたま",\
                  "http://weather.livedoor.com/forecast/rss/14/60.xml");
    print_weather("熊谷",\
                  "http://weather.livedoor.com/forecast/rss/14/61.xml");
    print_weather("秩父",\
                  "http://weather.livedoor.com/forecast/rss/14/62.xml");
    print_weather("東京",\
                  "http://weather.livedoor.com/forecast/rss/14/63.xml");
    print_weather("大島",\
                  "http://weather.livedoor.com/forecast/rss/14/64.xml");
    print_weather("八丈島",\
                  "http://weather.livedoor.com/forecast/rss/14/65.xml");
    print_weather("父島",\
                  "http://weather.livedoor.com/forecast/rss/14/66.xml");
    print_weather("千葉",\
                  "http://weather.livedoor.com/forecast/rss/14/67.xml");
    print_weather("銚子",\
                  "http://weather.livedoor.com/forecast/rss/14/68.xml");
    print_weather("館山",\
                  "http://weather.livedoor.com/forecast/rss/14/69.xml");
    print_weather("横浜",\
                  "http://weather.livedoor.com/forecast/rss/14/70.xml");
    print_weather("小田原",\
                  "http://weather.livedoor.com/forecast/rss/14/71.xml");
}

#---------------------------------------------------------------------
# get_weather - Livedoor 天気予報から現在の天気を取得
function print_weather(place, url) {
    #-----------------------------------------------------------------
    # 天気予報の RSS を取得
    #   一度テンポラリファイルに書き出します
    XMLMODE = 0;
    weather_url = "/inet/tcp/0/weather.livedoor.com/80";
    tmp_file = "weather.xml";
    ORS = RS = "\r\n\r\n";
    print "GET " url " HTTP/1.0" |& weather_url;
    weather_url |& getline header;
    while ((weather_url |& getline) > 0) {
        printf("%s\n", $0) > tmp_file;
    }
    close(weather_url);
    close(tmp_file);
    ORS = RS = "\n";
    #-----------------------------------------------------------------
    # 天気予報 RSS (XML) のパース
    #   xgawk の libexpat による XML のパース機能を使っています
    today = strftime("%m") + 0 "月" strftime("%d") "日";
    XMLMODE = 1;
    XMLCHARSET = "utf-8";
    while (getline < tmp_file > 0) {
        if (XMLCHARDATA) {
            data = $0;
        }
        if (XMLENDELEM == "title") {
            title = data;
            if (title ~ today) {
                split(title, weather, /[ \[\]-]+/);
                today_weather = weather[4];
                today_temp    = weather[5];
            }
        }
    }
    close(tmp_file);
    print place "の天気: " today_weather "、" today_temp;
}

実行結果

weather.jpg