前回は 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");
}
} 










コメントする