Search code examples
c#yamldotnet

Getting dynamic list entries from a YAML


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.)


Solution

  • 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);
        }
    }