How to parse a string yaml

I want to parse yaml in C # in such a way as to get a list of hash tables. I am 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 doesn't fail but gives me a null object.

My yaml looks like:

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

      

How can I parse my yaml and convert it to the type I want without doing it myself?

+3


source to share


1 answer


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

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 script shows that the code is working. I removed the second line from your code because it creates an object that is never used.

Also, it Hashtable

's probably not what you want to use. Since generics have been implemented in .NET, it is much better to use Dictionary

. It might be type safe. In this case, you can use Dictionary<string, string>

.

+6


source







All Articles