用yaml cpp解析yaml [英] Parsing yaml with yaml cpp
问题描述
我正在尝试解析Yaml usign yaml-cpp.这是我的yaml:
I am trying to parse a yaml usign yaml-cpp. This is my 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;
我收到消息:节点高度不存在".如何访问该字段(和其他字段?)
I am getting the message: "The node height doesn't exist". How can I access to that field (and the others?)
非常感谢!
推荐答案
与-
一起使用的语法创建数组元素.这意味着您正在创建(以JSON表示法):
The syntax you've used with the -
creates array elements. This means that you're creating (in JSON notation):
{configuration: [{height: 600}, {width: 800}, {velocity: 1}, {scroll: 30}]}
但是您想要的是:
{configuration: {height: 600, width: 800, velocity: 1, scroll: 30}}
幸运的是,解决方案很容易.只需删除错误的-
字符:
Luckily the solution is easy. Just remove the erroneous -
characters:
---
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
请注意,我还修复了宽度的错字,并在version: 1.0
如果您想知道如何实际访问现在的配置,则必须进行数组访问:
If you're wondering how you would actually access your configuration as it is now, you'd have to do an array access:
int height = basenode["configuration"][0]["height"].as<int>();
int height = basenode["configuration"][1]["width"].as<int>();
如果您确实想要这样,显然这会很讨厌,因为这意味着您不再需要使用键,而必须处理顺序问题或重新处理配置以摆脱数组级别.
Obviously this would be rather nasty if you actually wanted it like this since it means that you no longer get to use keys but would have to either have order matter or reprocess the config to get rid of the array level.
这篇关于用yaml cpp解析yaml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!