Search code examples
c#yamlyamldotnet

How to update a property value in YamlDotNet?


I'm trying to load an existing yaml file and update some of its properties. However- I'm trying not to override the other properties.

My yaml:

A:
  a1: value1
  a2: value2

Desired yaml:

A:
 a1: value1
 a2: modified

I currently have the following code, but I can only override the values of A:

string filePath = @"some\path\to\my.yaml";
TextReader reader = File.OpenText(filePath);
var yaml = new YamlStream();
yaml.Load(reader);
var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;

mapping.Children["A"] = new YamlMappingNode { {"a2", "modified"} };  //this overrides A and essentially deletes A.a1

I also tried this line, but it fails since a2 already exists:

(mapping.Children["A"] as YamlMappingNode).Add( "a2", "modified");

Solution

  • You can set the value like this:

    var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;
    ((YamlScalarNode)mapping.Children["A"]["a2"]).Value = "modified";
    

    Try it on fiddle