I've used this great library for YAML parser for 2 days. So, I may also have some mistakes. I use yaml-cpp ver0.6.2.
The main idea is to build your own structure.
After that, template specialization is used for specific types of transformation.
I think the structure of your document is not very good. It feels like nesting for std::map. I think you can look at this example Only for yaml file, Because these API are old
At last, you can pull the values into structures you've constructed.
I sorry, I'm poor in English. So show you my code. And you can ask me again if you have new problems.
Also, the code author is here. You may get more accurate answers from him .
struct Planet {
std::string earth;
};
struct Satellite {
std::string moon;
};
struct SolarSystem {
Planet p;
Satellite s;
};
namespace YAML {
template<>
struct convert<Planet> {
static Node encode(const Planet &rhs) {
Node node;
node["earth"] = rhs.earth;
return node;
}
static bool decode(const Node &node, Planet &rhs) {
if (!node.IsMap())
return false;
rhs.earth = node["earth"].as<std::string>();
return true;
}
};
template<>
struct convert<Satellite> {
static Node encode(const Satellite &rhs) {
Node node;
node["moon"] = rhs.moon;
return node;
}
static bool decode(const Node &node, Satellite &rhs) {
if (!node.IsMap())
return false;
rhs.moon = node["moon"].as<std::string>();
return true;
}
};
template<>
struct convert<SolarSystem> {
static Node encode(const SolarSystem &rhs) {
Node node;
node["my/planet"] = rhs.p;
node["my/satellite"] = rhs.s;
return node;
}
static bool decode(const Node &node, SolarSystem &rhs) {
if (!node.IsMap())
return false;
rhs.p = node["my/planet"].as<Planet>();
rhs.s = node["my/satellite"].as<Satellite>();
return true;
}
};
}
int main(void)
{
YAML::Node doc = YAML::LoadFile("path/to/your/file");
SolarSystem ss = doc["SOLAR-SYSTEM"].as<SolarSystem>();
std::cout << ss.p.earth << std::endl; // "blue"
std::cout << ss.s.moon << std::endl; // "white"
return 0;
}