4

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: something@some.com
              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: something@some.com
              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?

  • The only libraries that I know of that can currently preserve comments are [js yaml](https://github.com/eemeli/yaml), [libfyaml](https://github.com/pantoniou/libfyaml) and [ruamel.yaml](https://pypi.org/project/ruamel.yaml/) – tinita Sep 19 '20 at 10:21
  • [Related question](https://stackoverflow.com/questions/60891174/i-want-to-load-a-yaml-file-possibly-edit-the-data-and-then-dump-it-again-how). YamlDotNet seems to generate a [comment event](https://github.com/aaubry/YamlDotNet/blob/master/YamlDotNet/Core/Events/Comment.cs) when parsing so you can try processing the event stream instead of documents as described in the linked question. I don't know YamlDotNet well enough to craft a real answer. – flyx Sep 19 '20 at 12:54
  • Hi Sharan_Babu, did you ever solve this? I have the same requirement, I just want to update an existing yaml file and not lose comments in the process. – Simon Green Jun 06 '22 at 17:12
  • @SimonGreen No, I wrote some regex to extract the comments and store the corresponding location information before I deserialize which I later use to insert them back into the yaml – Sharan_Babu Feb 27 '23 at 20:26

0 Answers0