1

Can anyone help me. I'm trying to modify the yaml config.

This is the sample yaml:

person:
    # some comments
    name: "Test"
    # some comments
    age: 20

I want to modify only the age without affecting like comments and other infos. And then save it again to file.

But in my trial, the comments is not being save but only the deserialized data.

Thank you.

Maherz123
  • 67
  • 5

1 Answers1

-1
using YamlDotNet.Core;
using YamlDotNet.Core.Events;

using var reader = new StreamReader("test.yaml");

var scanner = new Scanner(reader, skipComments: false);
var parser = new Parser(scanner);

//using var writer = new StreamWriter("test2.yaml");
//var emitter = new Emitter(writer);
var emitter = new Emitter(Console.Out);

while (parser.MoveNext())
{
    if (parser.Current is Scalar scalar)
    {
        if (scalar.IsKey && scalar.Value == "age")
        {
            emitter.Emit(scalar);

            parser.MoveNext(); // move to age value

            emitter.Emit(new Scalar("30")); // new age value
            continue;
        }
    }
    emitter.Emit(parser.Current);
}

It almost works. The following result is obtained:

person
# some comments
:
  name: "Test"
  # some comments
  age: 30

The emitter violates the output. A colon is placed after the comment.

Do further research yourself.

Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49