使用yaml cpp解析yaml

Parsing yaml with yaml cpp

本文关键字:yaml 解析 cpp 使用      更新时间:2023-10-16

我正在尝试使用yaml-cpp解析一个yaml。这是我的网址:

--- 
configuration: 
  - height: 600
  - widht:  800
  - velocity: 1
  - scroll: 30
types: 
  - image: resources/images/grass.png
    name: grass
  - image: resources/images/water.png
    name: water
 version: 1.0

当我做

YAML::Node basenode = YAML::LoadFile("./path/to/file.yaml");
int height;
if(basenode["configuration"])
    if(basenode["configuration"]["height"]
       height = basenode["configuration"]["height"].as<int>();
    else
       cout << "The node height doesn't exist" << endl;
else
    cout << "The node configuration doesn't exist" <<  endl;

我得到消息:"节点高度不存在"。如何访问该字段(以及其他字段)

非常感谢!

您在-中使用的语法创建数组元素。这意味着您正在创建(JSON表示法):

{configuration: [{height: 600}, {width: 800}, {velocity: 1}, {scroll: 30}]}

但是你想要的是:

{configuration: {height: 600, width: 800, velocity: 1, scroll: 30}}

幸运的是,解决方法很简单。只需删除错误的-字符:

---
configuration: 
  height: 600
  width:  800
  velocity: 1
  scroll: 30
types: 
  - image: resources/images/grass.png
    name: grass
  - image: resources/images/water.png
    name: water
version: 1.0

请注意,我还修正了width的错别字,并删除了version: 1.0

之前的多余空间

如果你想知道如何访问你的配置,你必须做一个数组访问:

int height = basenode["configuration"][0]["height"].as<int>();
int height = basenode["configuration"][1]["width"].as<int>();

显然,如果你真的想要这样,这将是相当讨厌的,因为这意味着你不再使用键,但必须有顺序问题或重新处理配置,以摆脱数组级别。