c++ - 使用 yaml 有困难

标签 c++ yaml yaml-cpp

我想用 yaml 制作分层数据,不幸的是,我不太习惯这种格式,但我很乐意使用它,因为它对人类友好。

这是我的 yaml:

items:
    list1:
        itemA:
            item property a
        itemB:
    list2:
        itemC:
        itemD:

我正在使用 yaml-cpp,当我执行 doc["items"]["list1"]["itemA"] 时,我以 TypedKeyNotFound 异常结束,但我没有我想我很了解应该如何使用 yaml,我知道

doc["items"]["list1"]["itemA"].Type()

但我仍然有这个异常(exception)。

最佳答案

好吧,我设法更好地理解了 yaml 的工作原理,以及它是如何被解析的。我不想获取像这样的数据 a["fdfds"]["frwrew"]["vbxvxc"],因为我不想在解析之前要求知道 key 。我设法制作了一个代码,它主要使用 map 和序列来显示文档的结构,就在这里。

int spaces = 0; // define it in global scope, since unroll is a recursive function.
void unroll(const YAML::Node & node)
{
switch(node.Type())
{
    case YAML::NodeType::Map:       
    {
        for(auto it = node.begin(); it != node.end(); ++ it)
        {
            string s; it.first() >> s;
            indent();
            cout << s << "\n";
            const YAML::Node & dada = it.second();
            spaces ++;
            unroll(dada);
            spaces--;
            cout << "\n";
        }
        break;
    }

    case YAML::NodeType::Scalar:
    {
        indent();
        string s; node >> s;
        cout << "found scalar " << s << "\n";
        break;
    }
    case YAML::NodeType::Null:
    {
        indent();
        cout << "null";
        break;
    }
    case YAML::NodeType::Sequence:
    {
        //cout << "sequence";
        for(auto it = node.begin(); it != node.end(); ++ it)
        {
            string s; *it >> s;
            indent();
            cout << s << "\n";
        }
        break;
    }
    default: cout << "error: undefined";    break;
}
}

关于c++ - 使用 yaml 有困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9855012/

相关文章:

c# - RefCount 在 AtlUnadvise 调用后保持不变

c++ - 如何编译Detours Express 3.0?

go - 通过Golang形成YAML

yaml - windows 7下编译libyaml时编译报错

c++ - 使用 pybind11 包装 yaml-cpp 迭代器

C++以编程方式将字符串编码为字符串文字

c++ - QSqlite 在 Windows 和 Linux 上的不同行为

python - pickle `persistent_id` 的替代品?

c++ - 使用yaml-cpp错误解析YAML文件

c++ - 无法使用Qt Creator在Windows中构建yaml-cpp