首页 > 解决方案 > 遍历 YAML::Node 时如何获取当前节点的父节点?

问题描述

我在迭代YAML::Node. 到目前为止,我能够在层次结构向下时构建树。但是如果层次结构发生变化,我将无法获得父节点。

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

基于上述结构,我如何获得的父节点batmobile?假设,我这样迭代:

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?
}

标签: c++yamlyaml-cpp

解决方案


你不能,因为一般来说,一个 YAML 节点没有一个父节点。

YAML 文件的内容构成有向图,而不是树。例如,这个 YAML:

- &a 123
- foo: *a

定义两个项目的序列,标量节点123和包含单个键值对的映射节点。该对将标量foo作为键,将标量节点123作为值(别名由解析器解析)。这意味着标量节点123是从两个地方引用的,因此没有一个父节点。

另一个问题是,在 pairfoo: bar中,请求父节点bar会产生包含该对的映射,因为该对本身不是节点。但是您可能还想知道相应的密钥。

要点是,当下降到 YAML 图时,如果要回溯,则需要将路径存储在某处。


推荐阅读