How to add a mapping node to a YAML file without affecting comments

78 Views Asked by At

I have below yaml file

Input:

# Emp1 details
Employee1: &dept
  DeptCode: ABC
  Tower: T1

I want to add below yaml content with mapping key

# Emp2 details  
Employee2: &IT
  <<: *dept
  Block: firstfloor

So my final output:

# Emp1 details
Employee1: &dept
  DeptCode: ABC
  Tower: T1
  
# Emp2 details  
Employee2: &IT
  <<: *dept
  Block: firstfloor

We can achieve this by using the below code, but comments are removed from the YAML file while writing back. I have referred this Answer, but I am not sure how to add a mapping node by using emitter and parser.

        var reader = new StreamReader("Input.yaml");
        yaml.Load(reader);
        rootNode = (YamlMappingNode)yaml.Documents[0].RootNode;
        var newNode = new YamlMappingNode();
        newNode.Anchor = "IT";
        var dept = rootNode["dept"];
        newNode.Add("<<", dept);
        newNode.Add("Block", "firstfloor");
        rootNode.Add("Employee2",newNode )

 
0

There are 0 best solutions below