【问题标题】:How to get the parent node of the current node while iterating over YAML::Node?遍历 YAML::Node 时如何获取当前节点的父节点?
【发布时间】:2020-08-24 19:48:43
【问题描述】:

我在迭代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++ yaml yaml-cpp


    【解决方案1】:

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

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

    - &a 123
    - foo: *a
    

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

    另一个问题是在一对foo: bar 中,请求bar 的父节点将产生包含该对的映射,因为该对本身不是一个节点。但你可能也想知道对应的键。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-24
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多