How to preserve the comments when parsing yaml stream in C#?

2.2k Views Asked by At

I am using YamlDotNet for reading and writing yamls. The content of the yaml file is first loaded into YamlStream and the document is processed and modified. After the document is processed, the content is written back to the file. During this process, comments are not preserved and its crucial in my project to preserve the comments. E.g.,

Yaml file:

            users:
            - id: someid
              # comment that needs to be preserved
              emailAddress: [email protected]
              phone:

and the code is

        var input = new StringReader(Document);
        var yaml = new YamlStream();
        yaml.Load(input);
        
        var document =
            (YamlMappingNode)yaml.Documents[0].RootNode;

        /* document is updated here */

        var serializer = new SerializerBuilder().Build();
        var updatedYaml = serializer.Serialize(document);

        Console.WriteLine(updatedYaml);

and the expected output is

            users:
            - id: someid
              # comment that needs to be preserved
              emailAddress: [email protected]
              phone:

But the comments are not preserved in the actual output. I have looked at this thread about comment preservation, but it talks about emitting the comments with data member attributes. But in my scenario, I am not using any class to deserialize/serialize the yaml. I just want to maintain the existing comments in an yaml when reading and writing it back. Is it possible to do this using YamlDotNet?

0

There are 0 best solutions below