2010-03-17
boost1.41にXMLファイルの読み取り、書き込み機能が追加
boost1.41にXMLファイルの読み取り、書き込み機能が追加されていた。XMLだけでなく、JSONやINIにも対応している。
ほとんどboostのサンプルから持ってきて、ソースを書いてみた。
次のdebug_settings.xmlファイルがあることが前提。
<debug> <filename>debug.log</filename> <modules> <module>Finance</module> <module>Admin</module> <module>HR</module> </modules> <level>2</level> </debug>
#include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <string> #include <set> #include <exception> #include <iostream> struct debug_settings { std::string m_file; // ログファイル名 int m_level; // ログレベル std::set<std::string> m_modules; // ロギングが可能なモジュール }; // XMLファイルから読み出し void load(const std::string &filename) { // property tree オブジェクトの作成 using boost::property_tree::ptree; ptree pt; // XMLファイルの読み込み read_xml(filename, pt); // タグ名を指定してXMLの要素「ログファイル名」を取得 m_file = pt.get<std::string>("debug.filename"); // タグ名を指定してXMLの要素「ログレベル」を取得。取得できない場合は、0を設定する。 m_level = pt.get("debug.level", 0); // <debug>-<modules>の子要素(<module>)を全て取得して、set変数へ設定 BOOST_FOREACH(ptree::value_type &v, pt.get_child("debug.modules")) m_modules.insert(v.second.data()); } // XMLファイルへ書き出し void save(const std::string &filename) { // property tree オブジェクトの作成 using boost::property_tree::ptree; ptree pt; // ログファイル名を<debug>-<filename>へ設定 pt.put("debug.filename", m_file); // ログレベルを<debug>-<level>へ設定 pt.put("debug.level", m_level); // 全てのモジュール名をset変数から取得して、<debug>-<modules>-<module>へ設定 BOOST_FOREACH(const std::string &name, m_modules) pt.put("debug.modules.module", name, true); // XMLをファイルへ書き出し write_xml(filename, pt); } int main() { try { // ファイルの読み込み load("debug_settings.xml"); // ファイルの書き出し save("debug_settings_out.xml"); } catch (std::exception &e) { std::cout << "Error: " << e.what() << "\n"; } return 0; }
トラックバック - http://d.hatena.ne.jp/Softgels/20100317/1268845504

