---
title: "Edit YAML and keep its comments"
url: https://recursiveai.org/oneyaml/csharp/cookbook/edit-yaml-keep-comments/
description: "Change a value, remove a list item and add keys and list items in a YAML file from C# with OneYaml’s YamlDocument, with every other byte and comment kept."
version: "1.2.1"
---

# Edit YAML and keep its comments

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.

```csharp
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](https://recursiveai.org/oneyaml/csharp/cookbook/anchors-aliases-merge-keys/)).
- 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](https://recursiveai.org/oneyaml/csharp/docs/editing/). To change many values from a JSON document, use a patch: [merge or patch YAML](https://recursiveai.org/oneyaml/csharp/cookbook/patch-yaml/).

The same edit in Go, Rust and C#: [Edit YAML without losing comments](https://recursiveai.org/oneyaml/articles/edit-yaml-keep-comments/).
