如果您希望属性树反映层次结构,那么它需要编写自定义分析器。每个INI分析器documentation:
INI是一种简单的键值格式,具有单一级别的分区。 [...]并非所有的属性树都可以被序列化为INI文件。
由于单层剖分,my.section.subsection1
必须被视为一个关键,而不是一个层次结构路径。例如,my.section.subsection1.someProp1
路径可细分为:
key separator value
.----------^---------.^.---^---.
|my.section.subsection1|.|someProp1|
因为 “”是键的一部分,boost::property_tree::string_path
类型必须用不同的分隔符显式实例化。它可作为path_type
typedef在ptree
上提供。在这种情况下,我已选择使用 “/”:
ptree::path_type("my.section.subsection1/someProp1", '/')
用含有example.ini:
[my.section.subsection1]
someProp1=0
[my.section.subsection2]
anotherProp=1
下面的程序:
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
int main()
{
namespace pt = boost::property_tree;
pt::ptree propTree;
read_ini("example.ini", propTree);
boost::optional<uint32_t> someProp1 = propTree.get_optional<uint32_t>(
pt::ptree::path_type("my.section.subsection1/someProp1", '/'));
boost::optional<uint32_t> anotherProp = propTree.get_optional<uint32_t>(
pt::ptree::path_type("my.section.subsection2/anotherProp", '/'));
std::cout << "someProp1 = " << *someProp1
<< "\nanotherProp = " << *anotherProp
<< std::endl;
}
产生下列输出:
someProp1 = 0
anotherProp = 1
谢谢你的回复。是否(很容易)可以扩展默认的INI解析器,以便能够根据节名反映层次结构? – greydet
@greydet:我只简单地看了一下解析器代码,但看起来并不复杂。另一种选择是忽略解析,而是能够扩展和/或扁平化一个层级'ptree'到/从一个层级'ptree'。 –