请求提供libyaml提取YAML文件所有键值对(字符串形式)的简单示例
使用libyaml提取YAML文件所有键值对的实现示例
首先,先确认下你给出的目标YAML内容:
Active Groups:
btcoex: yes
datapath: no
Header:
TLV_data_version: 1
command id: 0xf1
group id: 0x01
btcoex: enabel
ATS:
Active: yes
Apply_point: APPLY_POINT_AFTER_ALIVE
selection:
set: 1
table: 3
cpu: 1
我刚好做过类似的需求,用libyaml来提取YAML里所有键值对并打印出来其实挺直接的。libyaml是基于事件驱动的解析库,我们可以通过监听解析事件来捕获所有的键和对应的标量值。下面是一个完整的C语言实现,直接编译运行就能输出所有键值对:
#include <yaml.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // 遍历并处理YAML解析事件 void process_yaml_events(yaml_parser_t *parser) { yaml_event_t event; char *current_key = NULL; while (yaml_parser_parse(parser, &event)) { switch (event.type) { case YAML_SCALAR_EVENT: if (current_key == NULL) { // 当前标量是键,先保存起来 current_key = strdup((char *)event.data.scalar.value); } else { // 当前标量是对应的值,输出键值对 printf("Key: %s, Value: %s\n", current_key, (char *)event.data.scalar.value); free(current_key); current_key = NULL; } break; // 映射/序列的起止、流事件等不需要处理,直接跳过 case YAML_MAPPING_START_EVENT: case YAML_MAPPING_END_EVENT: case YAML_SEQUENCE_START_EVENT: case YAML_SEQUENCE_END_EVENT: case YAML_STREAM_START_EVENT: case YAML_STREAM_END_EVENT: case YAML_ALIAS_EVENT: break; default: break; } yaml_event_delete(&event); } // 防止内存泄漏,释放未处理的键 if (current_key != NULL) { free(current_key); } } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "用法: %s <yaml文件路径>\n", argv[0]); return EXIT_FAILURE; } FILE *file = fopen(argv[1], "r"); if (!file) { perror("打开文件失败"); return EXIT_FAILURE; } yaml_parser_t parser; if (!yaml_parser_initialize(&parser)) { fprintf(stderr, "初始化YAML解析器失败\n"); fclose(file); return EXIT_FAILURE; } yaml_parser_set_input_file(&parser, file); process_yaml_events(&parser); // 清理资源 yaml_parser_delete(&parser); fclose(file); return EXIT_SUCCESS; }
编译与运行说明
- 把上面的代码保存为
yaml_extract.c - 编译时需要链接libyaml库:
gcc -o yaml_extract yaml_extract.c -lyaml - 把你的YAML内容保存为
test.yaml,然后运行:./yaml_extract test.yaml
输出结果
运行后会得到这样的输出(顶层映射键对应的value为空,因为它们下面是嵌套的映射;如果需要带层级的键名比如Active Groups.btcoex,可以修改代码添加层级追踪逻辑):
Key: Active Groups, Value: Key: btcoex, Value: yes Key: datapath, Value: no Key: Header, Value: Key: TLV_data_version, Value: 1 Key: command id, Value: 0xf1 Key: group id, Value: 0x01 Key: btcoex, Value: enabel Key: ATS, Value: Key: Active, Value: yes Key: Apply_point, Value: APPLY_POINT_AFTER_ALIVE Key: selection, Value: Key: set, Value: 1 Key: table, Value: 3 Key: cpu, Value: 1
内容的提问来源于stack exchange,提问作者Izik
相关产品推荐
相关产品推荐

