如何从父yaml节点获取完整的yaml节点子对象?

时间:2014-03-19 15:15:27

标签: yaml-cpp

我正在尝试在解析yaml文件时获取完整的节点对象。 我的yaml数据看起来类似于以下数据

---
Parent:
  Child1: ABC
  Child2:
    Subchild1: 123
    Subchild2: 456
  Child3: XYZ
...

我试图获取数据的方式是

YAML::Node parentNode = YAML::LoadFile(abc.yaml); // My yaml file name is abc

    if(!parentNode.IsNull())
    {
        if(parentNode.IsMap())
        {
            YAML::iterator it = parentNode.begin();
            std::cout << "Parent is " << it->first.as<std::string>() << std:endl; // Parent
            if(it->second.IsScalar())
            {
            }
            else if(it->second.IsMap())
            {
                YAML::Node rootChild = it->second;
                YAML::iterator chilItr = rootChild.begin();
                std::cout << "Child count is " << chilItr->second.size() << std:endl; // 3
                while(chilItr != rootChild.end())
                {
                    YAML::Node child = *chilItr;
                    if(child.IsMap()) //This causes exceetion
                    {
                        YAML::iterator ChildIterator = Child.begin();
                        std::cout << " Child is " << ChildIterator->first.as<std::string>() << std::endl;
                    }
                    chilItr++;
                }
            }
        }
    }

为什么child.IsMap()会抛出异常? 所以基本上要求是如何从父对象中获取子YAML节点对象?

1 个答案:

答案 0 :(得分:0)

我不认为您粘贴了您正在使用的确切YAML文件或确切代码,因为您对3的评论不会是使用您的示例打印的内容。这是基本的想法,使用您的示例YAML文件:

YAML::Node parentNode = YAML::LoadFile("abc.yaml");
if (parentNode.IsMap()) {
  YAML::iterator it = parentNode.begin();
  YAML::Node key = it->first;
  YAML::Node child = it->second;
  std::cout << "Parent is " << key.as<std::string>() << "\n"; // Parent
  if(child.IsMap()) {
    std::cout << "Child count is " << child.size() << "\n"; // 3

    // Now that you've got a map, you can iterate through it:
    for (auto it = child.begin(); it != child.end(); ++it) {
      YAML::Node childKey = it->first;
      YAML::Node childValue = it->second;

      // Now you can check the childValue object
      if(childValue.IsMap()) {
        // Iterate through it, if you like:
        for (auto it = childValue.begin(); it != childValue.end(); ++it) {
          // ...
        }
      }
    }
  }
}