31

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

  const ptree &settings = pt.get_child("settings", empty_ptree<ptree>());

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

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

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

}

但我得到下一个错误:

错误 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>()))
{

}

我得到:

错误 1 ​​错误 C2039:“empty_ptree”:不是“boost::property_tree”的成员

那么我该怎么办:如何迭代 Boost Ptree 并获得子 Ptree?

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

    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;
    }
}

这会编译,不会抛出任何异常,但不会抛出任何Sub data异常,它只是跳过这个循环。

更新 2:

嗯...我的 xml 中可能出了点问题 - 现在我使用该代码得到了正确的结果。

4

3 回答 3

33

属性树迭代器指向(key, tree)type 形式的对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.
}
于 2011-07-11T23:39:29.960 回答
27

使用 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
}
于 2013-12-06T18:30:42.873 回答
8

我在遍历 JSON 子节点时遇到了同样的问题

boost::property_tree::read_json(streamJSON, ptJSON);

如果你有这样的结构:

{
 playlists: [ {
   id: "1",
   x: "something"
   shows: [
    { val: "test" },
    { val: "test1" },
    { val: "test2" }
   ]
 },
 {
   id: "2"
   x: "else",
   shows: [
    { val: "test3" }
   ]
 }
 ]
}

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

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");
    }
}

我找不到有关路径选择器“显示”的任何信息。选择子数组。(注意最后的点)

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

希望这可以帮助某人。

于 2012-12-31T11:48:48.863 回答