我正在尝试使用 Boost 属性树来读取 INI
文件,其中包含部分中的属性,这些文件具有“组合”路径名。
例如我的 INI
文件如下所示:
[my.section.subsection1]
someProp1=0
[my.section.subsection2]
anotherProp=1
我是用下面的代码读的:
namespace pt = boost::property_tree;
pt::ptree propTree;
pt::read_ini(filePath, propTree);
boost::optional<uint32_t> someProp1 = pt.get_optional<uint32_t>("my.section.subsection1.someProp1");
问题是我从来没有得到someProp1
的值...
当我遍历第一个树级别时,我看到整个部分名称 my.section.subsection1
作为键。有没有办法让 read_ini
函数将带点的节名称解析为树状层次结构?
最佳答案
如果你想让属性树反射(reflect)层次结构,那么它需要编写一个自定义解析器。根据 INI 解析器 documentation :
INI is a simple key-value format with a single level of sectioning. [...] not all property trees can be serialized as INI files.
由于单级分段,my.section.subsection1
必须被视为键,而不是层次结构路径。例如,my.section.subsection1.someProp1
路径可以分解为:
key separator value
.----------^---------. ^ .---^---.
|my.section.subsection1|.|someProp1|
因为“.”是 key 的一部分,boost::property_tree::string_path
type 必须使用不同的分隔符显式实例化。它作为 ptree
上的 path_type
typedef 可用。在这种情况下,我选择使用“/”:
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
关于boost - 如何使用 boost 属性树获取 ini 文件的子部分内的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16673080/