How to parse a yaml string

max picture max · Sep 3, 2014 · Viewed 17.5k times · Source

I want to parse yaml in c# in such a way that I get a List of Hashtables. I'm using YamlDotNet. Here is my code:

TextReader tr = new StringReader(txtRawData.Text);
var reader = new EventReader(new MergingParser(new Parser(tr)));
Deserializer des = new Deserializer(); ;
var result = des.Deserialize<List<Hashtable>>(tr);

It does not fail but gives me a null object.

My yaml is like:

- Label: entry
  Layer: x
  id: B35E246039E1CB70
- Ref: B35E246039E1CB70
  Label: Info
  Layer: x
  id: CE0BEFC7022283A6
- Ref: CE0BEFC7022283A6
  Label: entry
  Layer: HttpWebRequest
  id: 6DAA24FF5B777506

How do I parse my yaml and convert it to the desired type without having to implement it on my own?

Answer

Antoine Aubry picture Antoine Aubry · Sep 4, 2014

The YAML document in your question is badly formatted. Each key must have the same indentation as the previous one. Since you mention that the code does not fail, I will assume that the actual document that you are parsing is correctly formatted.

I was able to successfully parse the document using the following code:

var deserializer = new Deserializer();
var result = deserializer.Deserialize<List<Hashtable>>(new StringReader(yaml));
foreach (var item in result)
{
    Console.WriteLine("Item:");
    foreach (DictionaryEntry entry in item)
    {
        Console.WriteLine("- {0} = {1}", entry.Key, entry.Value);
    }
}

This fiddle shows that the code works. I have removed the second line from your code because it creates an object that is never used.

Also, the Hashtable is probably not what you want to use. Since generics have been introduced in .NET, it is much better to use a Dictionary. It has the benefit of being type safe. In this case, you could use Dictionary<string, string>.