アーカイブ

Archive for 2007年11月

LINQ to XML:Webサービスを活用する

2007年11月20日 コメントを残す

※この投稿はMicrosoft Visual Studio 2008 Beta2で動作を確認しています。

LINQ to XMLはWeb上に存在する各種のサービスを利用するのにもっとも役に立つと思われます。
ここではlivedoorのお天気Webサービス(http://weather.livedoor.com/weather_hacks/webservice.html)を利用して明日の天気を確認できるページを作成してみます。

完成するとこんなページができあがります。

image_thumb

 

VS2008 ベータ2で新しくWebサイトを作成し、以下のソースを入力してください。

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Xml.Linq" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    XElement t = XElement.Load("http://weather.livedoor.com/forecast/rss/forecastmap.xml");

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // 県の一覧を取り出す
            var query = from s in t.Descendants("pref")
                        select (string)s.Attribute("title");

            this.DropDownList1.DataSource = query;
            this.DropDownList1.DataBind();
        }

    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.DropDownList2.Items.Clear();
        this.Panel1.Visible = false;

        if (this.DropDownList1.SelectedIndex > 0)
        {
            // 県内に設定されている地域の一覧を取り出す
            var q = from s in
                        (from s1 in t.Descendants("pref")
                         where (string)s1.Attribute("title") == this.DropDownList1.SelectedValue
                         select s1.Elements("city")).Single()
                    select new { title = (string)s.Attribute("title"), id = (int)s.Attribute("id") };

            this.DropDownList2.DataSource = q;
            this.DropDownList2.DataTextField = "title";
            this.DropDownList2.DataValueField = "id";
            this.DropDownList2.DataBind();
            this.DropDownList2.SelectedIndex = 0;
            this.DropDownList2_SelectedIndexChanged(this.DropDownList2, new EventArgs());
        }

    }
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.DropDownList2.SelectedIndex >= 0)
        {
            string tenkiUrl = "http://weather.livedoor.com/forecast/webservice/rest/v1?city=" + this.DropDownList2.SelectedValue + "&day=tomorrow";
            XElement w = XElement.Load(tenkiUrl);
           
            // 選択した地域の明日の天気情報の一部を取り出す
            var wq = w.DescendantsAndSelf("lwws")
                .Select(s => new { title = (string)s.Element("title"),
                    telop = (string)s.Element("telop"),
                    url = (string)s.Element("image").Element("url") })
                .Single();

            this.Label1.Text = wq.title;
            this.Label2.Text = wq.telop;
            this.Image1.ImageUrl = wq.url;
            this.Image1.AlternateText = wq.telop;
            this.Panel1.Visible = true;
        }

    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>明日の天気</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" AutoPostBack="True"
            OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
            <asp:ListItem>県を選択してください</asp:ListItem>
        </asp:DropDownList>
    </div>
    <asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
    </asp:DropDownList>
    <asp:Panel ID="Panel1" runat="server" Visible="False">
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server"></asp:Label>
        <br />
        <asp:Image ID="Image1" runat="server" />
    </asp:Panel>
    </form>
</body>
</html>

ソースの解説は、、、今回はパスします。
難しいことはしてませんので、元となるXMLと照らし合わせてソースを見ていけば何を行っているかはわかりやすいと思います。

XMLの階層はある程度意識する必要がありますが、XML特有の文法等を覚える必要がないのはやはり便利ですね。
個人的には業界に与えるインパクトが一番大きいのはLINQ to XMLなんじゃないか、と思いはじめてたりしています。

カテゴリー:.NET, LINQを楽しむ