Boost 1.46.1,属性树:如何遍历ptree接收子ptree

Boost 1.46.1, Property Tree: How to iterate through ptree receiving sub ptrees?

本文关键字:ptree 遍历 何遍历 属性 Boost      更新时间:2023-10-16

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

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

这表明可以(或者应该)从ptree中取出subptree

所以我假设我们可以用BOOST_FOREACH这样的方式遍历ptree:

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 p树迭代并获得子p树?

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

    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中可能出现了错误-现在我使用该代码得到了正确的结果。

属性树迭代器指向ptree::value_type类型的形式为(key, tree)的对。因此,遍历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.
}

使用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
}

我在遍历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");
    }
}

我找不到任何关于路径选择器"show ."选择子数组的内容。(注意末尾的圆点)

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