【问题标题】:Parsing yaml with yaml cpp使用 yaml cpp 解析 yaml
【发布时间】:2015-12-06 04:20:33
【问题描述】:

我正在尝试解析 yaml usign 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;

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

非常感谢!

【问题讨论】:

    标签: c++ yaml-cpp


    【解决方案1】:

    - 使用的语法创建数组元素。这意味着您正在创建(以 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
    

    请注意,我还修复了 widht 到 width 的拼写错误,并在 version: 1.0

    之前删除了多余的空格

    如果您想知道如何实际访问现在的配置,则必须进行数组访问:

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

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

    【讨论】:

    • 感谢@Corbin 让我清醒!效果很好!我没有找到很多文档和示例!
    猜你喜欢
    • 2020-10-14
    • 1970-01-01
    • 2015-05-14
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多