スポンサーリンク

Linq to XML 入門その2 (基本的ななクエリー)

それでは、Linqでの基本的なクエリーの方法について説明していきます。

今回はXMLデータとして、このBlogのRSS 2.0フィードを利用します。

では、まずRSSを表示してみましょう。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Document rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml");
Console.WriteLine(rss.Declaration);
//Console.WriteLine(rss.FirstNode);
Console.WriteLine(rss);
Document rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml"); Console.WriteLine(rss.Declaration); //Console.WriteLine(rss.FirstNode); Console.WriteLine(rss);
Document rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml");
Console.WriteLine(rss.Declaration);
//Console.WriteLine(rss.FirstNode);
Console.WriteLine(rss);

その表示結果の一部。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!--?xml version="1.0" encoding="utf-8"?-->
<rss version="2.0">
<channel>
<title>OPC Diary</title>
<link>http://www.isisaka.com/blog/
<description>私的ソフトウェア開発あれこれ。</description>
<language>ja</language>
<copyright>Copyright 2009</copyright>
<lastbuilddate>Thu, 14 May 2009 10:47:36 +0900</lastbuilddate>
<generator>http://www.sixapart.com/movabletype/</generator>
<docs>http://blogs.law.harvard.edu/tech/rss</docs>
<item>
<title>プログラム言語 Axum</title>
<description>
<!--[CDATA[<a rel="noopener noreferrer" target="_blank" href="http://msdn.microsoft.com/en-us/devlabs/dd795202.aspx"-->Axum<p></p> <p>.NET Framework上でEr
langっぽい(ぽいねあくまでも)並列言語実行環境を提供するプログラミング言語。Erlangっぽいので、基本的にメッセージパッ
シングで実行単位(Agentというらしい)間でデータ交換を行うようだ。</p> <p>これがこのまま製品化するとは思わないけど、
まぁF#の例もあるので、案外化けるかもだ。素直に考えればC#に取り込まれていくんだろうけど。</p>]]>
</description>
<link>http://www.isisaka.com/blog/archives/2009/05/_axum.html
<guid>http://www.isisaka.com/blog/archives/2009/05/_axum.html</guid>
<category domain="http://www.sixapart.com/ns/types#category">.NET</category>
<category domain="http://www.sixapart.com/ns/types#category">オブジェクト指向・システム開発</category>
<pubdate>Thu, 14 May 2009 10:47:36 +0900</pubdate>
</item></channel></rss>
<!--?xml version="1.0" encoding="utf-8"?--> <rss version="2.0"> <channel> <title>OPC Diary</title> <link>http://www.isisaka.com/blog/ <description>私的ソフトウェア開発あれこれ。</description> <language>ja</language> <copyright>Copyright 2009</copyright> <lastbuilddate>Thu, 14 May 2009 10:47:36 +0900</lastbuilddate> <generator>http://www.sixapart.com/movabletype/</generator> <docs>http://blogs.law.harvard.edu/tech/rss</docs> <item> <title>プログラム言語 Axum</title> <description> <!--[CDATA[<a rel="noopener noreferrer" target="_blank" href="http://msdn.microsoft.com/en-us/devlabs/dd795202.aspx"-->Axum<p></p> <p>.NET Framework上でEr langっぽい(ぽいねあくまでも)並列言語実行環境を提供するプログラミング言語。Erlangっぽいので、基本的にメッセージパッ シングで実行単位(Agentというらしい)間でデータ交換を行うようだ。</p> <p>これがこのまま製品化するとは思わないけど、 まぁF#の例もあるので、案外化けるかもだ。素直に考えればC#に取り込まれていくんだろうけど。</p>]]> </description> <link>http://www.isisaka.com/blog/archives/2009/05/_axum.html <guid>http://www.isisaka.com/blog/archives/2009/05/_axum.html</guid> <category domain="http://www.sixapart.com/ns/types#category">.NET</category> <category domain="http://www.sixapart.com/ns/types#category">オブジェクト指向・システム開発</category> <pubdate>Thu, 14 May 2009 10:47:36 +0900</pubdate> </item></channel></rss>

    
        
            OPC Diary
            http://www.isisaka.com/blog/
            私的ソフトウェア開発あれこれ。
            ja
            Copyright 2009
            Thu, 14 May 2009 10:47:36 +0900
            http://www.sixapart.com/movabletype/
            http://blogs.law.harvard.edu/tech/rss
            
                プログラム言語 Axum
                
                    Axum

.NET Framework上でEr langっぽい(ぽいねあくまでも)並列言語実行環境を提供するプログラミング言語。Erlangっぽいので、基本的にメッセージパッ シングで実行単位(Agentというらしい)間でデータ交換を行うようだ。

これがこのまま製品化するとは思わないけど、 まぁF#の例もあるので、案外化けるかもだ。素直に考えればC#に取り込まれていくんだろうけど。

]]>
http://www.isisaka.com/blog/archives/2009/05/_axum.html http://www.isisaka.com/blog/archives/2009/05/_axum.html .NET オブジェクト指向・システム開発 Thu, 14 May 2009 10:47:36 +0900

RSSフィードを受信して、表示できる事が確認できたでしょうか。

では、このデータからBlog記事の投稿日とタイトルの一覧を作りたいと思います。

RSS 2.0ではitemエレメントに各Blog記事のデータが入っています。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
XDocument rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml");
//XMLの木構造をたどって目的のElementに到達するやり方
var query = from x in rss.Element("rss").Elements("channel").Elements("item")
select x;
foreach (var i in query) {
DateTime pubDate = DateTime.Parse(i.Element("pubDate").Value);
Console.WriteLine(pubDate.ToString() + "\t: " + i.Element("title").Value);
XDocument rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml"); //XMLの木構造をたどって目的のElementに到達するやり方 var query = from x in rss.Element("rss").Elements("channel").Elements("item") select x; foreach (var i in query) { DateTime pubDate = DateTime.Parse(i.Element("pubDate").Value); Console.WriteLine(pubDate.ToString() + "\t: " + i.Element("title").Value);
XDocument rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml");
//XMLの木構造をたどって目的のElementに到達するやり方
var query = from x in rss.Element("rss").Elements("channel").Elements("item")
            select x;
foreach (var i in query) {
        DateTime pubDate = DateTime.Parse(i.Element("pubDate").Value);
        Console.WriteLine(pubDate.ToString() + "\t: " + i.Element("title").Value);

1行目ではRSSフィードを取り出しています。

3行目でLinqを使いRSSフィードからitemエレメントを取り出します。ここではRoorのrssエレメントから純にRSSの木構造たどってitemeエレメントまでを指定し検索もとを絞っています。itemエレメントは一つとは限らないのでElementsとして指定します。

5行目以降では検索結果をもとに更新日とタイトルをリスト表示します。

この様に特定のエレメントを検索対象とするには性格に木構造をたどる形で指定していく必要があり、その木構造が深いと指定するのが大変です。

そこで、Linq to XMLではDescendantsでエレメント名を指定すれば木構造をたどらずにダイレクトに指定する事が出来ます。(Descendantの意味は子孫)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
XDocument rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml");
//Descendantsを使う方法
var query = from x in rss.Descendants("item")
select x;
foreach (var i in query) {
DateTime pubDate = DateTime.Parse(i.Element("pubDate").Value);
Console.WriteLine(pubDate.ToString() + "\t: " + i.Element("title").Value);
}
XDocument rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml"); //Descendantsを使う方法 var query = from x in rss.Descendants("item") select x; foreach (var i in query) { DateTime pubDate = DateTime.Parse(i.Element("pubDate").Value); Console.WriteLine(pubDate.ToString() + "\t: " + i.Element("title").Value); }
XDocument rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml");
//Descendantsを使う方法
var query = from x in rss.Descendants("item")
            select x;
foreach (var i in query) {
    DateTime pubDate = DateTime.Parse(i.Element("pubDate").Value);
    Console.WriteLine(pubDate.ToString() + "\t: " + i.Element("title").Value);
}

先ほどと変わったのは3行目です。かなりスッキリ書けるようになったのがわかると思います。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
2009/05/14 10:47:36 : プログラム言語 Axum
2009/05/11 19:03:02 :2回静岡 IT Pro 勉強会のご案内
2009/05/10 21:53:00 :30回 NT-Committee2関東勉強会
2009/05/10 21:21:41 : プリンタを買いました。(HP C309a)
2009/05/10 9:57:29 : キヤノン インクジェットプリンタのヘッド交換ができないので買い換えてやる!
2009/05/10 8:20:50 : そろそろCorei7かな。。
2009/05/10 0:06:41 : デザイナー目線でのFlash vs. Silverlight(2)
2009/05/09 15:42:19 : Linq to XML 入門その1 (XML文書の作り方)
2009/05/08 12:16:11 : Japan Windows Server : Hyper-V Server R2 Release Candidate 公開
2009/05/08 7:34:02 : Windows 7 向けリモートサーバ管理ツール
2009/05/06 23:34:56 : exFATはやはりブートメディアを作ることはできない
2009/05/05 15:48:55 : Vistaの供給は20111月まで、メインストリームサポートは20124月までらしい
2009/05/05 15:12:37 : Windows 7 RC アメリカでは一般公開
2009/05/04 23:32:40 : Windows 7(x64) をVirtualBoxに入れてみた。
2009/05/02 6:43:33 : プログラミングに適したフォント
2009/05/14 10:47:36 : プログラム言語 Axum 2009/05/11 19:03:02 : 第2回静岡 IT Pro 勉強会のご案内 2009/05/10 21:53:00 : 第30回 NT-Committee2関東勉強会 2009/05/10 21:21:41 : プリンタを買いました。(HP C309a) 2009/05/10 9:57:29 : キヤノン インクジェットプリンタのヘッド交換ができないので買い換えてやる! 2009/05/10 8:20:50 : そろそろCorei7かな。。 2009/05/10 0:06:41 : デザイナー目線でのFlash vs. Silverlight(2) 2009/05/09 15:42:19 : Linq to XML 入門その1 (XML文書の作り方) 2009/05/08 12:16:11 : Japan Windows Server : Hyper-V Server R2 Release Candidate 公開 2009/05/08 7:34:02 : Windows 7 向けリモートサーバ管理ツール 2009/05/06 23:34:56 : exFATはやはりブートメディアを作ることはできない 2009/05/05 15:48:55 : Vistaの供給は2011年1月まで、メインストリームサポートは2012年4月までらしい 2009/05/05 15:12:37 : Windows 7 RC アメリカでは一般公開 2009/05/04 23:32:40 : Windows 7(x64) をVirtualBoxに入れてみた。 2009/05/02 6:43:33 : プログラミングに適したフォント
2009/05/14 10:47:36     : プログラム言語 Axum
2009/05/11 19:03:02     : 第2回静岡 IT Pro 勉強会のご案内
2009/05/10 21:53:00     : 第30回 NT-Committee2関東勉強会
2009/05/10 21:21:41     : プリンタを買いました。(HP C309a)
2009/05/10 9:57:29      : キヤノン インクジェットプリンタのヘッド交換ができないので買い換えてやる!
2009/05/10 8:20:50      : そろそろCorei7かな。。
2009/05/10 0:06:41      : デザイナー目線でのFlash vs. Silverlight(2)
2009/05/09 15:42:19     : Linq to XML 入門その1 (XML文書の作り方)
2009/05/08 12:16:11     : Japan Windows Server : Hyper-V Server R2 Release Candidate 公開
2009/05/08 7:34:02      : Windows 7 向けリモートサーバ管理ツール
2009/05/06 23:34:56     : exFATはやはりブートメディアを作ることはできない
2009/05/05 15:48:55     : Vistaの供給は2011年1月まで、メインストリームサポートは2012年4月までらしい
2009/05/05 15:12:37     : Windows 7 RC アメリカでは一般公開
2009/05/04 23:32:40     : Windows 7(x64) をVirtualBoxに入れてみた。
2009/05/02 6:43:33      : プログラミングに適したフォント

表示結果はこうなります。

それでは、where句を使った条件検索を試してみます。

以下のコードでは5/11以降に更新された記事のリストを表示するようにします。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
XDocument rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml");
//Descendantsを使う方法
var query = from x in rss.Descendants("item")
where DateTime.Parse(x.Element("pubDate").Value) > DateTime.Parse("2009/5/11")
select x;
foreach (var i in query) {
DateTime pubDate = DateTime.Parse(i.Element("pubDate").Value);
Console.WriteLine(pubDate.ToString() + "\t: " + i.Element("title").Value);
}
XDocument rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml"); //Descendantsを使う方法 var query = from x in rss.Descendants("item") where DateTime.Parse(x.Element("pubDate").Value) > DateTime.Parse("2009/5/11") select x; foreach (var i in query) { DateTime pubDate = DateTime.Parse(i.Element("pubDate").Value); Console.WriteLine(pubDate.ToString() + "\t: " + i.Element("title").Value); }
XDocument rss = XDocument.Load(@"http://www.isisaka.com/blog/index.xml");
//Descendantsを使う方法
var query = from x in rss.Descendants("item")
            where DateTime.Parse(x.Element("pubDate").Value) > DateTime.Parse("2009/5/11")
            select x;
foreach (var i in query) {
    DateTime pubDate = DateTime.Parse(i.Element("pubDate").Value);
    Console.WriteLine(pubDate.ToString() + "\t: " + i.Element("title").Value);
}

4行目のwhere句で5/11以降のデータのみ抽出するようにしています。

以下が実行結果です。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
2009/05/14 10:47:36 : プログラム言語 Axum
2009/05/14 10:47:36 : プログラム言語 Axum
2009/05/14 10:47:36     : プログラム言語 Axum

11日以降に投稿した記事のリストが表示されています。

今回はここまで。

RSSを加工したい事はよくあるので、少しぐらいは参考になったでしょうか。

次回はもう少し複雑なクエリについて説明したいと思っています。ただ、データを作るのが難儀なのでしばらくお待ちください。。。

コメント

  1. OPC Diary より:

    Linq to XML 入門その1 (XML文書の作り方)

    準備 これから数回に分けてLinq to XMLの基礎的な使い方についてまとめ…

  2. […] Linq to XML 入門その2 (基本的ななクエリー) […]

タイトルとURLをコピーしました