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

前端 未结 3 1366
情话喂你
情话喂你 2020-12-25 12:34

First of all I shall say that I think I got how it should be done but my code will not compile any way I try. I based my assumption on this official example of empty ptree t

相关标签:
3条回答
  • 2020-12-25 13:09

    The property tree iterators point to pairs of the form (key, tree) of type ptree::value_type. The standard loop for iterating through the children of the node at path therefore looks like:

    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.
    }
    
    0 讨论(0)
  • 2020-12-25 13:12

    I had the same problem with iterating trough JSON sub nodes

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

    If you have a structure like:

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

    You can iterate trough child nodes like this:

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

    I could not find anything about path selector "shows." to select sub array. (notice the dot at the end)

    Some good documentation can be found here: http://kaalus.atspace.com/ptree/doc/index.html

    Hope this helps someone.

    0 讨论(0)
  • 2020-12-25 13:16

    Using C++11, you can use the following to iterate through all the children of the node at 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
    }
    
    0 讨论(0)
提交回复
热议问题