0

My input YAML looks like

menu:
  - 'key one': 'first'
  - 'key two': 'second'

so quite simple. The sub-keys for menu are arbitrary values so there can be anykey:anyvalue.

Now I'm using YamlReader to get hold of these menu entries in a way that I can deal with key and value one after the other.

In this loop

var yaml = new YamlStream();
yaml.Load(reader);

foreach (var child in ((YamlMappingNode)yaml.Documents[0].RootNode).Children)
{
    string cName = child.Key.ToString();

I can access menu. But how can I loop through the kv-pairs in child.value?

(Probably it's something obvious but I really got stuck here.)

qwerty_so
  • 35,448
  • 8
  • 62
  • 86

1 Answers1

1

We need to iterate the Children collection on the node like:

var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;

var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("menu")];

foreach (YamlMappingNode item in items)
{
    foreach(var child in item.Children)
    {
        Console.WriteLine(child.Key + " - " + child.Value);
    }
}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • I used that sort of a fall-back solution: `var items ...`. However, since I looped already to `menu` and got that in `child` in my above code, isn't there a shorter way to access these `items` from `child`? That's what got me confused originally. – qwerty_so Mar 12 '21 at 12:45
  • @qwerty_so there might be a way to dynamically go without the root name but not in my knowledge too – Ehsan Sajjad Mar 12 '21 at 12:49
  • So I wasn't lookig for something hidden, but simply I had to go the "crude" path ;-) – qwerty_so Mar 12 '21 at 12:55