2013-05-21 77 views
0

我试图使用Boost属性树来读取INI包含部分内的属性的文件具有“合成”路径名。如何使用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函数解析节点名称作为树层次结构?

回答

3

如果您希望属性树反映层次结构,那么它需要编写自定义分析器。每个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 
+0

谢谢你的回复。是否(很容易)可以扩展默认的INI解析器,以便能够根据节名反映层次结构? – greydet

+0

@greydet:我只简单地看了一下解析器代码,但看起来并不复杂。另一种选择是忽略解析,而是能够扩展和/或扁平化一个层级'ptree'到/从一个层级'ptree'。 –