Search code examples
c#.net-8.0yamldotnet

How do I edit the indentation used when serializing a yaml string using yamldotnet in C#?


I managed to generate a YAML string. The default indentation is 2 characters but i need it to be 4 characters. As this is required by the application that will be processing this data. But I have not managed to succeed to achieve this.

Here is my code:

 var yamlSerializer = new SerializerBuilder()
     .Build();

 string yaml;
 using (var writer = new StringWriter())
 {
     var _settings = new EmitterSettings();
     Console.WriteLine(_settings.BestIndent);
     _settings.WithBestIndent(4);
     var _emitter = new Emitter(writer, _settings);
     yamlSerializer.Serialize(_emitter, dictionary);
     yaml = writer.ToString();
 }

 Console.WriteLine(yaml);

Here the output:

cars:
  bmw:
    model: 1 series
    catagory: coupe
    year: 2008
  nissan:
    model: 300zx
    catagory: hatchback
    year: 1996
  toyota:
    model: 4runner
    catagory: suv
    year: 2015
  audi:
    model: a8
    catagory: sedan
    year: 2017

And it should be like this:

cars:
    bmw:
        model: 1 series
        catagory: coupe
        year: 2008
    nissan:
        model: 300zx
        catagory: hatchback
        year: 1996
    toyota:
        model: 4runner
        catagory: suv
        year: 2015
    audi:
        model: a8
        catagory: sedan
        year: 2017

Solution

  • As stated in the comments by Progman. The WithBestIndent() method does not change the current settings object.

    Here the adjusted code that gives the desired result:

    string yaml;
     using (var writer = new StringWriter())
     {
         var _settings = new EmitterSettings();
         Console.WriteLine(_settings.BestIndent);
         _settings = _settings.WithBestIndent(4);
         var _emitter = new Emitter(writer, _settings);
         yamlSerializer.Serialize(_emitter, dictionary);
         yaml = writer.ToString();
     }
    
     Console.WriteLine(yaml);