Boost.PropertyTree
概述
1、它是一种容器,特点是层次结构,键值对保存,但不排序。
2、可以解析XML、Json、INI配置文件。
结构如下:
struct ptree
{
data_type data; // data associated with the node
list< pair<key_type, ptree> > children; // ordered list of named children
};
使用
1、读写XML文件
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <vector>
#include <set>
#include <exception>
#include <iostream>
namespace pt = boost::property_tree;
int main(){
pt::ptree tree;
//read
pt::read_xml(filename, tree);
m_file = tree.get<std::string>("debug.filename");
m_level = tree.get<int>("debug.level", 0);
BOOST_FOREACH(pt::ptree::value_type &v, tree.get_child("debug.modules")) {
std::cout<<v.second.data();
}
//write
tree.put("debug.filename", "AfterModify");
tree.put("debug.level", "0");
std::vector<std::string> modulename = {"first","second","third"}
BOOST_FOREACH(const std::string &name, modulename)
tree.add("debug.modules.module", name);
pt::write_xml(filename, tree);
}
2、读写Json文件
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>
namespace pt=boost::property_tree;
int main()
{
pt::ptree tree;
pt::read_json("E:\\Example\\BoostDemo\\Property_tree\\resources\\demo.json",tree);
std::cout << tree.get<std::string>("menu.bar","null");
pt::write_json("E:\\Example\\BoostDemo\\Property_tree\\resources\\demo1.json",tree);
return 0;
}