Boost 1.46.1,属性树:如何迭代ptree接收子ptree?

Rel*_*lla 30 c++ boost subtree boost-propertytree boost-foreach

首先,我要说我认为我应该怎么做但我的代码不会以任何方式编译我尝试.我的假设基于这个空ptree技巧的官方例子.在那里你可以找到下一行:

  const ptree &settings = pt.get_child("settings", empty_ptree<ptree>());
Run Code Online (Sandbox Code Playgroud)

这表明从(或应该)可以从ptree中获取subptree.

所以我假设我们可以用BOOST_FOREACH这样的方式迭代到ptree :

BOOST_FOREACH(const boost::property_tree::ptree &v,
    config.get_child("servecies"))
{

}
Run Code Online (Sandbox Code Playgroud)

但我得到下一个错误:

错误1错误C2440:'初始化':无法从'std :: pair <_Ty1,_Ty2>'转换为'const boost :: property_tree :: ptree&'

或者如果我尝试

BOOST_FOREACH(boost::property_tree::ptree &v,
    config.get_child("servecies", boost::property_tree::empty_ptree<boost::property_tree::ptree>()))
{

}
Run Code Online (Sandbox Code Playgroud)

我明白了:

错误1错误C2039:'empty_ptree':不是'boost :: property_tree'的成员

那我该怎么做:如何通过Boost Ptree迭代并得到子Ptrees?

更新: 我也试过这样的代码

    BOOST_FOREACH(boost::property_tree::ptree::value_type &v,
    config.get_child("path.to.array_of_objects"))
{
    std::cout << "First data: " << v.first.data() << std::endl;
    boost::property_tree::ptree subtree = (boost::property_tree::ptree) v.second ;
    BOOST_FOREACH(boost::property_tree::ptree::value_type &vs,
        subtree)
    {
        std::cout << "Sub data: " << vs.first.data() << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

这编译,不会抛出任何exeptions但不会cout任何Sub data,它只是通过这个循环斜倚.

更新2:

嗯...在我的xml中可能出错了 - 现在我用该代码得到了正确的结果.

ant*_*kos 32

属性树迭代器指向(key, tree)类型形式的对ptree::value_type.因此,迭代遍历节点子节点的标准循环path如下所示:

BOOST_FOREACH(const ptree::value_type &v, pt.get_child(path)) {
    // v.first is the name of the child.
    // v.second is the child tree.
}
Run Code Online (Sandbox Code Playgroud)


Ela*_*782 26

使用C++ 11,您可以使用以下内容遍历节点的所有子节点path:

ptree children = pt.get_child(path);
for (const auto& kv : children) {
    // kv is of type ptree::value_type
    // kv.first is the name of the child
    // kv.second is the child tree
}
Run Code Online (Sandbox Code Playgroud)


Eva*_*ans 5

迭代通过JSON子节点我遇到了同样的问题

boost::property_tree::read_json(streamJSON, ptJSON);
Run Code Online (Sandbox Code Playgroud)

如果你有一个像这样的结构:

{
 playlists: [ {
   id: "1",
   x: "something"
   shows: [
    { val: "test" },
    { val: "test1" },
    { val: "test2" }
   ]
 },
 {
   id: "2"
   x: "else",
   shows: [
    { val: "test3" }
   ]
 }
 ]
}
Run Code Online (Sandbox Code Playgroud)

您可以像这样迭代子节点:

BOOST_FOREACH(boost::property_tree::ptree::value_type &playlist, ptJSON.get_child("playlists"))
{
    unsigned long uiPlaylistId = playlist.second.get<unsigned long>("id");
    BOOST_FOREACH(boost::property_tree::ptree::value_type &show, playlist.second.get_child("shows."))
    {
       std::string strVal = show.second.get<std::string>("val");
    }
}
Run Code Online (Sandbox Code Playgroud)

我找不到关于路径选择器"show"的任何信息.选择子数组.(注意最后的点)

可以在这里找到一些好的文档:http: //kaalus.atspace.com/ptree/doc/index.html

希望这有助于某人.