Boost C++ XML parsing -
i familiar on how parse xml boost, if xml has , including 3 levels. however, having trouble following example:
(please ignore slight lack of logic in xml since adaptation of cannot change. structure important)
<content> <room> <roomname>livingroom</roomname> <description> <color>red</color> <size>small</size> </description> <description> <color>blue</color> <size>big</size> </description> </room> <room> <roomname>bathroom</roomname> <description> <color>green</color> <size>medium</size> </description> </room> </content>
i have tried this:
struct room { std::string roomname; std::string roomcolor; std::string roomsize; }; void parseroomsxml(){ boost::property_tree::ptree tree; boost::property_tree::read_xml("./rooms.xml", tree); boost::property_tree::ptree formats = tree.get_child("content"); boost_foreach( boost::property_tree::ptree::value_type const& f, formats ) { if( f.first == "room" ) { room s; s.roomname = f.second.get<std::string>("roomname"); std::cout<<s.roomname<<std::endl; const boost::property_tree::ptree & attributes = formats.get_child("room"); boost_foreach( boost::property_tree::ptree::value_type const& v, attributes ) { if (v.first == "description"){ s.roomcolor = v.second.get<std::string>("color"); s.roomsize = v.second.get<std::string>("size"); std::cout<< s.roomcolor << " " <<s.roomsize; } } } } }
the result first room parsed correctly, second room has description of first one:
=========================
output:
livingroom
red small
blue big
bathroom
red small
blue big
========================
expected result be:
livingroom
red small
blue big
bathroom
green medium
===================================
thanks in advance, appreciated, since trying used boost.
the problem seems in statement: const boost::property_tree::ptree & attributes = formats.get_child("room");
you can iterate on children using following code:
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; color = vs.second.get<std::string>("color"); roomsize = vs.second.get<std::string>("size"); } }
Comments
Post a Comment