Recursive AI

Edit YAML and keep its comments

All oneyaml C# recipes

Change a YAML file from C# the way a person would: one value, one list item, one new key. Every comment, blank line and quote elsewhere stays as it was.

C#
using OneYaml;
 
using var doc = YamlDocument.Parse("""
    # App settings, edited by hand and by tools.
    server:
      host: 0.0.0.0
      port: 8080      # behind the load balancer
 
    # Feature flags
    features:
      - auth
      - legacy-export   # remove after the 2.0 release
      - metrics
 
    """);
 
doc.Set("/server/port", 9090);        // its trailing comment stays
doc.Remove("/features/1");            // its comment goes with it
doc.Root["server"]["timeout"] = "30s"; // a new key, laid out like its siblings
doc.Add("/features/-", "audit-log");  // appended in the list's own style
 
Console.Write(doc);
Text
# App settings, edited by hand and by tools.
server:
  host: 0.0.0.0
  port: 9090      # behind the load balancer
  timeout: 30s
 
# Feature flags
features:
  - auth
  - metrics
  - audit-log

Good to know

  • Each value keeps its style. Set writes in the old value’s style when it can hold the new value: plain stays plain, quotes stay, and a block literal stays a block literal. Otherwise only that value falls back to a style that can.
  • Comments are kept, not modeled. The comment after a changed value stays, and a removed item takes its comment with it. There is no API to read, add or move comments.
  • New keys go at the end of their mapping and copy its layout. Add("/list/-", value) appends to a sequence, and an index equal to the count appends too.
  • An edit through an alias is refused, with YamlErrorCategory.RefusedAlias, because it would change every place that shares the node (anchors and aliases).
  • A new plain string such as yes stays plain under YAML 1.2. If YAML 1.1 programs also read the file, set QuoteYaml11Lookalikes = true in YamlDocumentOptions so such strings are quoted.

What an edit keeps, and what it doesn’t, is in Editing. To change many values from a JSON document, use a patch: merge or patch YAML.

The same edit in Go, Rust and C#: Edit YAML without losing comments.