Boost Property_Tree iterators, how to handle them?

前端 未结 3 1205
野的像风
野的像风 2021-02-07 10:00

I am sorry, I asked a question about the same topic before, but my problem concerns another aspect of the one described there (How to iterate a boost...).

Take a look at

3条回答
  •  梦谈多话
    2021-02-07 10:31

    I agree with Andry, and find the documentation of property_tree to be extremely minimal at the least. I needed ptree for loading identical objects with different settings, and had trouble figuring out what the iterator iterates over, what type it returns, and whether or not it will remain on the objects level, or go through every node BFS-like. Finally, I managed to get my code working for a case similar to the following:

    settings file:

    
        true
        
    
    
        false
        
    
    

    First, I added a constructor for my object, which can initialize on a ptree. Note that I'm using the get with default option, to prevent exception on failed get()'s:

    object::object(const boost::property_tree::ptree &pt_)
    {
        enable = pt_.get("enable", true); // usage is: get(path, default)
        label  = pt_.get("label", "empty");
    }
    

    Finally the following code loads both objects, and places them in a map:

    std::map objects_map;
    
    // parse settings file and add loggers
    if(filesystem::exists(logger_settings_file))
    {
        boost::property_tree::ptree pt;
    
        read_xml(logger_settings_file, pt);
        BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt)
        {
            objects_map[v.first] = my_object(v.second);
        }
    }
    

    So, to answer my own questions:

    • The iterator iterates over the settings file without descending into lower levels. Running the above code you will find that the loop iterates twice - one time for each object in the XML file.
    • The iterator returns a value_type object which resembles a pair, and has the first and second accessors. v.first is an std::string holding the parent node (in my case "object1", "object2"), and v.second is a boost::property_tree::ptree, which can be used to parse the fields of the object.

提交回复
热议问题