【问题标题】:how to get properties within subsections of a ini file with boost property tree?如何使用 boost 属性树在 ini 文件的子部分中获取属性?
【发布时间】:2013-05-16 09:38:36
【问题描述】:

我正在尝试使用 Boost 属性树来读取 INI在部分中包含属性的文件具有“组合”路径名。

例如我的INIfile 看起来像这样:

[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 函数将带点的部分名称解析为树层次结构?

【问题讨论】:

    标签: boost ini boost-propertytree ptree


    【解决方案1】:

    如果您希望属性树反映层次结构,则需要编写自定义解析器。根据 INI 解析器 documentation:

    INI 是一种简单的键值对格式,具有单级分段。 [...] 并非所有属性树都可以序列化为 INI 文件。

    由于单级分段,my.section.subsection1 必须被视为键,而不是层次结构路径。例如,my.section.subsection1.someProp1 路径可以分解为:

               key    separator  value 
     .----------^---------. ^ .---^---.
    |my.section.subsection1|.|someProp1|
    

    因为“。”是键的一部分,boost::property_tree::string_path 类型必须用不同的分隔符显式实例化。它在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
    

    【讨论】:

    • 感谢您的回复。是否可以(轻松地)扩展默认的 INI 解析器,以便能够根据部分名称反映层次结构?
    • @greydet:我只是简单地看了一下解析器代码,但它似乎并没有过于复杂。另一种选择是忽略解析,而是能够将单个级别 ptree 扩展到/从分层 ptree 展开和/或展平。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    相关资源
    最近更新 更多