RapidXML 触ってみる
なんか3人の方にブックマークして頂いたようなので、もう少しマシな情報を。
RapidXMLに簡単にXMLを処理させてみました。
お手頃なXMLのデータがなかったので、自分のはてなブックマークページをローカルに落として使いました。
程よくタグの綴じ漏れがあるデータだったのでRapidXMLの評価には返ってよかった。・・・でもimgとかmetaとかlinkとか閉じていないのはダメだと思う。
サンプルプログラムはこんな感じ。本家より少し変な事もやっているのでちと長くなってます。
あんまり深くは触ってないけど、TinyXMLよりもはRapidXMLの方が楽に書けると思う。
#include <iostream> #include <fstream> #include "rapidxml.hpp" int main(int argc, char* argv[]) { // check parameter if (argc < 2) { std::cerr << "usage : " << argv[0] << " <input file>" << std::endl; return 1; } // open file const char* filename = argv[1]; std::ifstream input(filename); if (input.is_open() == false) { std::cerr << "[ERROR] can't open the file : " << filename << std::endl; return 1; } // read file std::string text; { int filesize = input.rdbuf()->in_avail(); text.reserve(filesize); } getline(input, text, '\0'); // parse xml data rapidxml::xml_document<> doc; try { doc.parse<0>(&text[0]); } catch(rapidxml::parse_error& ex) { int position = (int)ex.where<char>() - (int)&text[0]; std::cerr << "parse error (" << position << ") : " << ex.what() << std::endl; return 1; } // traverse DOM tree std::cout << "name of first node is " << doc.first_node()->name() << std::endl; rapidxml::xml_node<>* node = doc.first_node("html"); std::cout << "node <html> has value " << node->value() << std::endl; for (rapidxml::xml_attribute<>* attr = node->first_attribute(); attr; attr = attr->next_attribute()) { std::cout << "Node <html> has attirbute " << attr->name() << " "; std::cout << "with value " << attr->value() << std::endl; } for (rapidxml::xml_node<>* sibling = node->first_node(); sibling; sibling = sibling->next_sibling()) { std::cout << "Node <html> has sibling node " << sibling->name() << std::endl; } return 0; }
で実行結果例。
% ./example01 bookmark.xhtml name of first node is html node <html> has value Node <html> has attirbute xml:lang with value ja Node <html> has attirbute xmlns with value http://www.w3.org/1999/xhtml Node <html> has attirbute lang with value ja Node <html> has sibling node head Node <html> has sibling node body