Boost Property_Tree iterators, how to handle them?

Andry picture Andry · Jan 4, 2011 · Viewed 25.5k times · Source

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 the following code:

#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/algorithm/string/trim.hpp>
int main(int argc, char** argv) {
     using boost::property_tree::ptree;
     ptree pt;
     read_xml("try.xml", pt);
     ptree::const_iterator end = pt.end();
     for (ptree::const_iterator it = pt.begin(); it != end; it++)
           std::cout << "Here " << it->? << std::endl;
}

Well, as I got told told in the question I mentioned, there is the possibility to use iterators on property_tree in Boost, but I do not know what type it is, and what methods or properties I can use.

Well, I assume that it must be another ptree or something representing another xml hierarchy to be browsed again (if I want) but documentation about this is very bad. I do not know why, but in boost docs I cannot find nothing good, just something about a macro to browse nodes, but this approach is one I would really like to avoid.

So getting to my question here: Once getting the iterator on a ptree, how can I access node name, value, parameters (a node in a xml file)? Thankyou

Answer

Andriy Tylychko picture Andriy Tylychko · Jan 4, 2011

print complete tree:

void print(boost::property_tree::ptree const& pt)
{
    using boost::property_tree::ptree;
    ptree::const_iterator end = pt.end();
    for (ptree::const_iterator it = pt.begin(); it != end; ++it) {
        std::cout << it->first << ": " << it->second.get_value<std::string>() << std::endl;
        print(it->second);
    }
}