2014-03-19 222 views
1

我想在解析yaml文件时获取完整的节点对象。 我YAML的数据看起来类似下面的数据如何从父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节点对象?

回答

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) { 
      // ... 
     } 
     } 
    } 
    } 
} 
+0

对不起,有评论。我刚刚输入了代码作为我的要求的摘要。它不是实际的代码。 –

+0

我实际上想要一个带有键和值的子节点,以便我可以将该节点传递给另一个函数,而不是单独发送值。我不想使用迭代器中的键和值创建新节点,而是将键和值作为参考传递给子节点。 –

+0

我实际上想要一个同时具有键和值的子节点,以便我可以将节点的引用传递给另一个函数,而不是单独发送值。我不想用迭代器中的键和值创建新节点,而是传递节点的引用。 –