首先,我要说,我认为我知道应该如何做,但我的代码不会编译任何我尝试的方式。我的假设是基于这个空的ptree技巧的官方例子。在这里你可以找到下一行:
const ptree &settings = pt.get_child("settings", empty_ptree<ptree>());这表明从ptree中提取子树是可能的(或者应该是)。
因此,我假设我们可以以这样的方式通过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树迭代并获得子树呢?
更新:我也尝试过这样的代码
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可能出了问题--现在我得到了正确的结果。
发布于 2011-07-11 23:39:29
属性树迭代器指向类型为(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.
}发布于 2013-12-06 18:30:42
使用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
}发布于 2012-12-31 11:48:48
我在迭代槽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
希望这能帮上忙。
https://stackoverflow.com/questions/6656380
复制相似问题