简介
Property Tree(属性树)提供这样一种数据结构 : 存储任意深度嵌套的, 由某种key索引的, 数据树 。每个树上的节点保存它自己的value加上一个它的子节点的key和节点的有序链表。 Property Tree允许通过多个key的连接(表示节点的路径)很方便的访问树上的每一个节点。
另外,库(boost::property_tree) 提供了解析器, 可以将其他利于表示为树格式的数据( 比如 XML , JSON, INI ...) 生成Property Tree 。
Property Tree 是用途广泛的数据结构, 但它尤其擅长存储配置文件。Property Tree 通过了它自己的,Property Tree特殊的接口,并且每个节点对于子节点而言是STL完整的。
概念上, 一个节点类似于:
struct ptree
{
data_type data; // data associated with the node
list< pair<key_type, ptree> > children; // ordered list of named children
};
key_type 和 data_type 可以被配置成各种类型,但是通常是std::string 或者 std::wstring, 解析器仅能为这两种树工作。
实用接口
毫无疑问, boost总是会提供最方便的接口。
解析/ 写回 Json
- read_json( XXX , ptree )
- write_json( XXX , ptree)
- XXX 可以是一个ostringstream 流
- XXX 可以是一个文件名
增删查
- add_child ( path , ptree ) 向一个ptree添加子树。
- add_value(Type t) 为一个ptree添加数据
erase( iterater ) 删除子树。
get_child( path) 获得子树
- get_value() 获得自己的数据
get(path) 获得子树的数值
get_optional 处理空值
遍历
像map一样遍历 key 是string value 是 ptree
实例
int main(){
boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini("tt.ini",pt);
boost::property_tree::ptree tesss = pt.get_child("tesss");
std::cout<<tesss.get<std::string>("test") <<"\n";
for(auto & pair : tesss){
std::cout<<pair.first<<" = " <<pair.second.get_value<std::string>()<<std::endl;
}
return 0;
}
读取 :
[tesss]
test=Hello ini