前回は xpath で簡単に RSS からタイトルを抜き出す方法を書いたのですが、下記のようにデフォルトの名前空間が指定されている RSS1.0 では、xpath "//title/item" では 取得できないことが分かりました。

<rdf:RDF
  xmlns="http://purl.org/rss/1.0/"
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xml:lang="ja">

つまり、xpath "//item" は名前空間なしの素の item エレメントであって、デフォルト名前空間の下にある item という名前のエレメントにはマッチしないということらしいのです。じゃあどうやってそれを xpath で表すかというと、表す方法はないとか…あわわ。

ということで、以下のような感じでなんとかクリア。 get_children で地道に辿っていく方法もあるのですが、 RSS1.0 と 2.0 では item ノードの階層が違うので、共通で使えるコードとなると xpath の方が単純に書けていいと思います。厳密さを撮るか簡便さを取るか、ですね。

#include <iostream>
#include <libxml++/document.h>
#include <libxml++/parsers/domparser.h>
#include <libxml++/nodes/node.h>
#include <libxml++/nodes/element.h>
#include <libxml++/nodes/textnode.h>

using namespace std;
using namespace xmlpp;

int main ( void ){
   DomParser parser;
   parser.parse_memory( string_rss );
   Element *root = parser.get_document()->get_root_node();
   NodeSet items = root->find("//*[name()='item']");

   for( NodeSet::iterator it = items.begin(); 
          it != items.end(); it++ ){
      const NodeSet value = (*it)->find( "//*[name()='title']" );
      string title = dynamic_cast< Element *>(value[0])
                       ->get_child_text()->get_content();
      cout << "Title: " + title << endl;
   }

   return 0;
}
find ではなく get_children を使って書くと item の NodeList を取るのは以下のようになります。それほど複雑でもないので xpath に慣れていない場合はこっちの方が良いかも。
   /* RSS 2.0 */
   Node::NodeList items = root->get_children("item");
   /* RSS 1.0 */
   if( items.empty() ){
      const Node::NodeList ch = root->get_children("channel");
      if( ! ch.empty() ){
         items = ch.front()->get_children("item");
      }
   }

トラックバック(0)

このブログ記事を参照しているブログ一覧: libxml++ を使ってみる: xpath とデフォルト名前空間

このブログ記事に対するトラックバックURL: http://tsuyuguchi.com/mt/mt-tb.cgi/338

コメントする

最近の画像

料理が少し楽しくなるかもしれないグッズ
江戸糸あやつり人形
江戸糸あやつり人形
おうち、
新橋青空大判将棋
「天体の回転について」読了
「幼年期の終り」読了
「数学ガール/フェルマーの最終定理」読了
ハリー・ポッター 最終巻
もう炊飯器いらないかも

私の本棚

 

自転車走行距離

Flickr Photos

なかのひと

Y!ログール

このサイトについて

あわせて読みたいブログパーツ

2008年11月

            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30            

アーカイブ

My Update

  • Loading...

その他