[C#] Twitter Search APIをWebClientから使用する例

12:07 AM on 2011年6月24日 ,

private class Tweet
{
    public string ID { get; set; }
    public string Title { get; set; }
    public string Published { get; set; }
    public string Source { get; set; }
    public Uri Image { get; set; }
    public string Author { get; set; }
}

private void GetTweets()
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += (sender, e) =>
    {
        if (e.Error == null)
        {
            XDocument doc = XDocument.Parse(e.Result);

            // XNamespace
            XNamespace nsDef = "http://www.w3.org/2005/Atom";
            XNamespace twitter = "http://api.twitter.com/";

            var items = from item in doc.Descendants(nsDef + "entry")
                        let author = item.Element(nsDef + "author")
                        select new Tweet()
                        {
                            ID = item.Element(nsDef + "id").Value,
                            Title = item.Element(nsDef + "title").Value,
                            Published = item.Element(nsDef + "published").Value,
                            Source = item.Element(twitter + "source").Value,
                            Author = author.Element(nsDef + "name").Value,
                            Image = new Uri((from XElement xe in item.Descendants(nsDef + "link")
                                             where xe.Attribute("type").Value == "image/png"
                                             select xe.Attribute("href").Value).First())
                        };

            foreach (Tweet t in items)
            {
                // 取得したTweetを処理
            }
        }
        else
        {
            // error
        }
    };

    client.DownloadStringAsync(new Uri("http://search.twitter.com/search.atom?q=" + HttpUtility.UrlEncode("#test")));
}