Recursive AI

Patch the second document in a YAML stream in C#

OneYaml is a free, open-source YAML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Pass document: 1 to patch the second document in YAML text separated by ---.

Terminal
dotnet add package OneYaml

Targets .NET 8 and .NET 10 (example).

C#
using OneYaml;
 
const string yaml =
    "port: 8080\n---\nport: 8081\n";
using var stream = YamlDocument.Parse(yaml);
var patch = new YamlPatch()
    .Replace("/port", 9090);
stream.ApplyPatch(patch, document: 1);
Console.Write(stream);

Unzip the example, then dotnet run.

The snippet prints:

Text
port: 8080
---
port: 9090

If there’s no second document, ApplyPatch throws a YamlException with category PatchPath.

Variations

Use a JSON Merge Patch. This merges a partial JSON object into the selected document. Replace the patch builder and ApplyPatch call. Console.Write(stream) still prints both documents:

C#
stream.ApplyMergePatch(
    """{"port":9090}""", document: 1);

The short answer

Parse the whole YAML stream once. Pass document: 1 to ApplyPatch to select its second document, then write the whole YamlDocument. /port is a JSON Pointer path relative to the selected document’s root, like /spec/replicas for a nested key. The path doesn’t include the document number. Here the first port remains 8080; only the second becomes 9090.

How do I edit one document in a multi-document YAML file?

A single YAML file can hold several documents. Here --- marks the start of the second one. Pass the entire text to the parser rather than splitting the text yourself. OneYaml exposes the roots via Documents and the count via Documents.Count. That gives you an index for an edit or a way to tell whether the expected document exists.

The first document is index 0 and the second is index 1. Omitting the argument targets the first, which can be easy to miss if every document has the same key. When you know the document by its position, pass the index explicitly. When the order could change, identify the document by a distinguishing value before patching it. The editing guide describes how to address document roots.

Does a YAML patch change the other documents in the stream?

No. A patch call targets one document. The document editor keeps untouched text, so printing the result gives you the first document, the --- boundary and the updated second document. The output is the whole stream, not just the selected root. ApplyPatch doesn’t overwrite an input file; the example prints the text so you can see what would be written.

If you need to patch two documents, make two calls with different indexes. A failing call rolls back its own operations. It doesn’t undo a separate call that already succeeded; keep the edits in memory and wait until all calls succeed before saving the result. See patch errors and rollback.

All oneyaml C# recipes