Skip to content

Instantly share code, notes, and snippets.

@endJunction
Created November 7, 2012 11:08
Show Gist options
  • Save endJunction/4030890 to your computer and use it in GitHub Desktop.
Save endJunction/4030890 to your computer and use it in GitHub Desktop.
boost::property_tree and xml config example
<coupling>
<P algorithm="serial">
<M name="flow1" type="GROUNDWATER_FLOW" />
<P algorithm="parallel">
<M name="compoundA" type="MASS_TRANSPORT" />
<M name="compoundB" type="MASS_TRANSPORT" />
</P>
</P>
</coupling>
# g++ --std=c++11 -I /usr/include/boost/ x.cpp && ./a.out
coupling
name
type
M
compoundA
MASS_TRANSPORT
M
compoundB
MASS_TRANSPORT
#include <tuple>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
int main(void)
{
const std::string filename = "config.xml";
// Create an empty property tree object
using boost::property_tree::ptree;
ptree pt;
read_xml(filename, pt);
for(const ptree::value_type &v : pt)
{
std::cout << v.first << std::endl;
}
std::cout << std::endl;
for(const ptree::value_type &v : pt.get_child("coupling.P.P.M.<xmlattr>"))
{
std::cout << v.first << std::endl;
}
std::cout << std::endl;
for(const auto& i : pt.get_child("coupling.P.P"))
{
std::string name;
ptree sub_pt;
std::tie(name, sub_pt) = i;
if (name != "M")
continue;
std::cout << name << std::endl;
std::cout << "\t" << sub_pt.get<std::string>("<xmlattr>.name") << std::endl;
std::cout << "\t" << sub_pt.get<std::string>("<xmlattr>.type") << std::endl;
}
return EXIT_SUCCESS;
}
@amelnychuk
Copy link

Hey man this is like the best boost C++ xml parser example I've come across.

pt.get_child("coupling.P.P.M.") this line tottaly explained everything to me.

Thanks so much!

@etienneschmitt
Copy link

I agree.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment