【问题标题】:confused by YAML::NodeType::Undefined with yaml-cpp被 YAML::NodeType::Undefined 和 yaml-cpp 混淆了
【发布时间】:2016-08-24 14:35:06
【问题描述】:

我有一个尝试使用 yaml-cpp 解析的测试 yaml 文件。

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,以便我可以根据需要解析包含。

【问题讨论】:

  • YAML 文件中无需在 thingX.yaml 周围加上引号
  • @Anthon 感谢您提供的信息...我习惯了 json,其中似乎几乎所有内容都需要引号。

标签: c++ parsing yaml yaml-cpp


【解决方案1】:

嗯,您的顶级 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"];
// ...

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我刚找到这个,正要发表评论!感谢您及时的回复。我刚刚删除了多余的顶级 testConfig。
    猜你喜欢
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 2022-10-04
    • 2015-05-14
    相关资源
    最近更新 更多