Search code examples
c++yamlyaml-cpp

How to get the parent node of the current node while iterating over YAML::Node?


I am building a tree structure while iterating over a YAML::Node. So far, i am able to build the tree when the hierarchy goes downwards. But if there is change in heirarchy i am not able to get the parent node.

batman:
  type: super hero
  entity: ""
  natural: yes
  attributes:
    powers:
      whip:
        x: ""
        y: ""
      batmobile:
        x: ""
        y: ""

Based on the above structure, how do i get the parent node of batmobile? Assuming, i am iterating like this:

for (YAML::const_iterator it = node.begin(); it != node.end(); ++it)
{
    std::cout << it->first.as<std::string>() << std::endl; // prints batmobile
    
   // how to get the parent node of batmobile?
}

Solution

  • You can't because in general, a YAML node does not have a single parent.

    The content of a YAML file constitutes a directed graph, not a tree. For example, this YAML:

    - &a 123
    - foo: *a
    

    Defines a sequence of two items, the scalar node 123 and a mapping node containing a single key-value pair. That pair has the scalar foo as key and the scalar node 123 as value (the alias gets resolved by the parser). This means that the scalar node 123 is referenced from two places and thus does not have a single parent.

    Another problem would be that within a pair foo: bar, asking for the parent node of bar would yield the mapping containing the pair, because the pair itself is not a node. But you probably also want to know the corresponding key.

    The takeaway is that when descending into a YAML graph, you need to store the path you take somewhere if you want to backtrack.