c++yamlyaml-cpp

Traverse through nodes with a path and change a value in a YAML File using yaml-cpp


I am trying to load and alter a YAML file using yaml-cpp.

I have a string that determines a path thought a yaml, e.g. "node1/node2/node3", it gets split at '/' and then traverses through the YAML.

After that, I try to save the YAML.

My problem is that somehow the YAML does not get altered the way I would like it. Ive written a minimal example:

#include <yaml-cpp/yaml.h>
#include <iostream>

int main()
{
    const std::string test_yaml =
    "node1:\n"
    "  node2:\n"
    "    node3:\n"
    "      name: \"somevalue\"";
    
    YAML::Node root = YAML::Load(test_yaml);
    
    std::list<std::string> path;
    path.push_back("node1");
    path.push_back("node2");
    path.push_back("node3");
    
    YAML::Node traverse = root;
    
    for (const std::string &path_element: path)
    {
        traverse = traverse[path_element];
    }
    
    traverse["name"] = "something else";
    
    YAML::Emitter e;
    e << root;
    
    std::cout << e.c_str() << std::endl;
    
    return 0;
}

What I would expect to happen is that the YAML looks like:

node1:
  node2:
    node3:
      name: something else

but instead the result is:

node2:
  name: something else

and I cannot figure out whats wrong.

The code above can be compiled using g++ -o yamlex yamlex.cc $(pkg-config --libs --cflags yaml-cpp)


Solution

  • To avoid changing the node, use reset:

    for (const std::string &path_element: path)
    {
        traverse.reset(traverse[path_element]);
    }