使用 YAML::Emitter 将嵌套映射和序列写入 yaml 文件

Writing nested maps and sequences to a yaml file using YAML::Emitter

我一直在尝试使用 YAML::Emitter 输出一个 yaml 文件。例如,我需要这样的东西作为我的 yaml 文件。

annotations:
  - run:
     type: range based
     attributes:
      start_frame:
       frame_number: 25
      end_frame:
       frame_number: 39     

到目前为止,使用我的代码

for (auto element : obj)
{
    basenode = YAML::LoadFile(filePath);  //loading a file throws exception when it is not a valid yaml file

    //Check if metadata is already there
    if (!basenode["file_reference"])
    {
        writeMetaData(element.getGttStream(), element.getTotalFrames(), element.getFileHash());
    }

    annotationNode["annotations"].push_back(element.getGestureName());

    annotationNode["type"] = "range based";
    output << annotationNode;

    attributesNode["attributes"]["start_frame"]["frame_number"] = element.getStartFrame();

    attributesNode["attributes"]["end_frame"]["frame_number"] = element.getEndFrame();

    output << typeNode;
    output << attributesNode;

    ofs.open(filePath, std::ios_base::app);
    ofs << std::endl << output.c_str();
}

我得到这样的输出

annotations:
  - run
type: range based
---
attributes:
 start_frame:
  frame_number: 26
 end_frame:
  frame_number: 57

我希望最近推送的序列项下的 "type" 和 "attributes" 进入 "annotations",随后所有后续节点都相同。

我什至尝试过使用这样的东西

annotationNode[0][type] = "range based"

输出是这样的

0: type: "range based"

如何获取序列"annotations"中最近推送的项目?

如果您正在构建根节点,annotationNode,那么只需构建并输出一次即可。您不需要将 typeNodeattributesNode 写入发射器。例如,您可以写

YAML::Node annotationNode;
for (auto element : obj) {
  YAML::Node annotations;
  annotations["name"] = element.getGestureName();
  annotations["type"] = ...;
  annotations["attributes"] = ...;
  annotationNode["annotations"] = annotations;
}

output << annotationNode;