Question

I have a YAML file like:

top:
  names:
    - name: john1
    - name: john2
    - name: john3
    - name: john.doe

Now I have to remove top/names/name(john.doe). How can I achieve that with yaml-cpp? My code is:

void deleteNode(string id)
{
    YAML::Node config = YAML::LoadFile("doc.yaml");
    for (int i = 0; i < config["top"]["names"].size(); i++)
    {
        if(config["top"]["names"][i]["name"].as<string>() == id)
        {
            config["top"]["names"].remove(config["top"]["names"][i]);
            break;
        }
    }
}
deleteNode("john.doe");

This doesn't seem to do anything.

Was it helpful?

Solution

Since you're dealing with a sequence, you have to remove a node by its index:

void deleteNode(string id) {
    YAML::Node config = YAML::LoadFile("doc.yaml");
    YAML::Node names = config["top"]["names"];
    for (int i = 0; i < names.size(); i++) {
        if(names[i]["name"].as<string>() == id) {
            names.remove(i);
            break;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top