关于C#:Yaml-cpp(新API)-嵌套图/序列组合和迭代

Yaml-cpp (new API) - nested map / sequence combinations and iteration

此api的地图和序列处理存在一些基本问题。说我有以下结构:

1
2
3
4
foo_map["f1"] ="one";
foo_map["f2"] ="two";
bar_map["b1"] ="one";
bar_map["b2"] ="two";

我希望将其转换为以下YAML文件:

1
2
3
4
5
6
7
Node:
    - Foo:
      f1 : one
      f2 : two
    - Bar:
      b1 : one
      b2 : two

我可以这样做:

1
2
3
4
node.push_back("Foo");
node["Foo"]["b1"] ="one";
...
node.push_back("Bar");

但是,最后一行的节点现在已从序列转换为映射,但出现异常。我能做到这一点的唯一方法是通过输出地图:

1
2
3
4
5
6
7
Node:
    Foo:
      f1 : one
      f2 : two
    Bar:
      b1 : one
      b2 : two

这是我无法读回此类文件的问题。如果我在Node上进行迭代,那么即使没有异常,我也无法获取节点迭代器的类型。

1
2
3
4
5
6
7
YAML::Node::const_iterator n_it = node.begin();

for (; n_it != config.end(); n_it++) {
        if (n_it->Type() == YAML::NodeType::Scalar) {
            // throws exception
        }
    }

这应该很简单,但是却让我发疯!


YAML文件

1
2
3
4
5
6
7
Node:
    - Foo:
      f1 : one
      f2 : two
    - Bar:
      b1 : one
      b2 : two

可能不是您所期望的。它是一个映射,具有单个键/值对;键是Node,值是一个序列;并且该序列的每个条目都是具有三个键/值对的映射,并且与Foo相关的值为null。最后一部分可能不是您期望的。我猜您想要的更像是您实际得到的东西,即:

1
2
3
4
5
6
7
Node:
    Foo:
      f1 : one
      f2 : two
    Bar:
      b1 : one
      b2 : two

现在的问题是如何解析此结构。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
YAML::Node root = /* ... */;
YAML::Node node = root["Node"];

// We now have a map node, so let's iterate through:
for (auto it = node.begin(); it != node.end(); ++it) {
  YAML::Node key = it->first;
  YAML::Node value = it->second;
  if (key.Type() == YAML::NodeType::Scalar) {
    // This should be true; do something here with the scalar key.
  }
  if (value.Type() == YAML::NodeType::Map) {
    // This should be true; do something here with the map.
  }
}