与yaml度过了一段艰难时期

时间:2012-03-24 19:53:16

标签: 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()

但我仍然有这个例外。

1 个答案:

答案 0 :(得分:1)

我设法更好地了解yaml的工作方式,以及如何解析它。我不希望得到这样的数据[“fdfds”] [“frwrew”] [“vbxvxc”],因为我不想在解析之前要求知道密钥。我设法制作了一个代码,用于显示主要使用地图和序列的文档结构,这里就是。

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;
}
}