Search code examples
c#.net.net-coreyamlyamldotnet

Reading Yamldotnet with c#


i've some problems when i'm trying to read a Yaml file using c# and need help to finish this task , how can i read a such Yaml file into variables so i can treat them .

FileConfig: 
  sourceFolder: /home
  destinationFolder: /home/billy/my-test-case
  scenarios: 
  - name: first-scenario 
    alterations: 
    - tableExtension: ln
      alterations: 
      - type: copy-line
        sourceLineIndex: 0
        destinationLineIndex: 0
      - type: cell-change
        sourceLineIndex: 0
        columnName: FAKE_COL
        newValue: NEW_Value1
    - tableExtension: env
      alterations: 
      - type: cell-change
        sourceLineIndex: 0
        columnName: ID
        newValue: 10

Here is my code

string text = System.IO.File.ReadAllText(@"test.yaml");

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




Solution

  • The easiest way is to create a C# model of your document. Then you are able to use the Deserializer to fill that model with the data present into the document. A possible model for your document would be:

    public class MyModel
    {
        [YamlMember(Alias = "FileConfig", ApplyNamingConventions = false)]
        public FileConfig FileConfig { get; set; }
    }
    
    public class FileConfig
    {
        public string SourceFolder { get; set; }
        public string DestinationFolder { get; set; }
        public List<Scenario> Scenarios { get; set; }
    }
    
    public class Scenario
    {
        public string Name { get; set; }
        public List<Alteration> Alterations { get; set; }
    }
    
    public class Alteration
    {
        public string TableExtension { get; set; }
        public List<TableAlteration> Alterations { get; set; }  
    }
    
    public class TableAlteration
    {
        public string Type { get; set; }
        public int SourceLineIndex { get; set; }
        public int DestinationLineIndex { get; set; }
        public string ColumnName { get; set; }
        public string NewValue { get; set; }
    }
    

    You can deserialize to that model as follows:

    var deserializer = new DeserializerBuilder()
        .WithNamingConvention(CamelCaseNamingConvention.Instance)
        .Build();
    
    var obj = deserializer.Deserialize<MyModel>(yaml);
    

    You can run this code here: https://dotnetfiddle.net/SRABFM

    Of course, the model that I suggest here is very naive and with more knowledge about your domain model, you will certainly be able to come up with a better one.