混淆了YAML :: NodeType :: Undefined with yaml-cpp

时间:2016-08-24 14:35:07

标签: c++ parsing yaml yaml-cpp

我有一个测试yaml文件,我试图使用yaml-cpp进行解析。

test.yaml

testConfig:
    # this points to additional config files to be parsed
    includes:
        required: "thing1.yaml"
        optional: "thing2.yaml"
    #some extraneous config information 
    foo: 42
    bar: 394
    baz: 8675309

我解析它我得到testConfig.Type()返回YAML::NodeType::Map。这是预期的行为。

然后,我尝试解析包含以获取我无法迭代的必需值或可选值,因为includes.Type()返回YAML::NodeType::Undefined。我对yaml和yaml-cpp都很陌生,所以任何有助于向我展示我出错的地方都会受到赞赏。

解析代码:

{includes and other such nonsense} 
            .
            .
            .
YAML::Node configRoot = YAML::LoadFile(path.c_str() );
if( configRoot.IsNull() )
{   
    SYSTEM_LOG_ERROR("Failed to load the config file: %s.",
                    path.c_str());
    return false;
}   

YAML::Node includes = configRoot["includes"];
/*  ^^^^^^^^^^^^^^^
 * I believe that here lies the issue as includes is undefined and
 * therefore I cannot iterate over it.
 */
for( auto it = include.begin(); it != include.end(); ++it )
{   
    // do some fantastically brilliant CS voodoo!
}
            .
            .
            .
{ more C++ craziness to follow }

解: 我删除了不必要的顶级configTest,以便我可以根据需要解析包含。

2 个答案:

答案 0 :(得分:2)

嗯,您的顶级YAML文档确实没有包含名为includes的密钥。它只包含一个名为testConfig的密钥。你应该先访问它:

// ...
YAML::Node configRoot = YAML::LoadFile(path.c_str())["testConfig"];
// ...

或者,如果您想明确检查testConfig是否存在:

// ...
YAML::Node configRoot = YAML::LoadFile(path.c_str());
// do check her as in your code
YAML:Node testConfig = configRoot["testConfig"];
// check if testConfig is a mapping here
YAML::Node includes = testConfig["includes"];
// ...

答案 1 :(得分:1)

您正在查看configRoot["includes"],但地图中的顶级密钥为testConfig。请改用configRoot["testConfig"]

相关问题