boost - 如何使用 boost 属性树获取 ini 文件的子部分内的属性?

标签 boost ini boost-propertytree

我正在尝试使用 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/

相关文章:

c++ - 围绕 boost::ptree 头痛的模板化类

c++ - 如何将 boost::gregorian::date 转换为 mm/dd/yyyy 格式,反之亦然?

c++ - 什么是 C++17 等价于 boost::filesystem::unique_path()?

c++ - 优化使用 Boost 的项目构建的最佳方法是什么?

php parse_ini_file oop & 深度

c++ - Boost:如何从现有属性树中获取子树?

c++ - 同一 (Boost) DLL 的多个版本可以在同一进程中共存吗?

xml - 数据结构格式(YAML 或诸如此类)的往返解析,保留注释,用于编写配置

python - 如何将应用程序设置保存在配置文件中?

c++ - 从 boost::property_tree 读取数组出现空白