LINQ to XML を試してみる
ここのところ、仕事の合間に LINQ でちょこちょこと遊んでいたりします。
んで、先週末のわんくま同盟大阪勉強会 #20 のとりこびとさんのセッションでも取り上げられていた LINQ to XML を使って、はてなの RSS を取ってみました。
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace Jp.Mkns.Test { class LinqToXmlTest { static void Main() { XDocument xdoc = XDocument.Load("http://d.hatena.ne.jp/masa-k/rss"); XNamespace nsRss = @"http://purl.org/rss/1.0/"; XNamespace nsDC = @"http://purl.org/dc/elements/1.1/"; XNamespace nsContent = @"http://purl.org/rss/1.0/modules/content/"; var itemList = from xseq in xdoc.Root.Elements() where xseq.Name.LocalName.Equals("item") select new { Title = xseq.Element(nsRss + "title").Value, Url = xseq.Element(nsRss + "link").Value, Author = xseq.Element(nsDC + "creator").Value, Date = DateTime.Parse(xseq.Element(nsDC + "date").Value), Desc = xseq.Element(nsRss + "description").Value, Content = xseq.Element(nsContent + "encoded").Value }; foreach (var item in itemList) { Console.WriteLine(" Title : " + item.Title); Console.WriteLine(" URL : " + item.Url); Console.WriteLine(" Author : " + item.Author); Console.WriteLine(" Date : " + item.Date.ToString()); Console.WriteLine(" Desc : " + item.Desc); Console.WriteLine(); } } } }
XMLDocument で一生懸命解析していたあの頃 (=.NET 2.0) は何だったんだか。。。