Write one YAML document per object.
dotnet add package OneYamlTargets .NET 8 and .NET 10; the download uses .NET 10.
using OneYaml; Pool[] pools = [new("web"), new("jobs")]; var yaml = YamlSerializer.SerializeAll(pools); Console.Write(yaml); record Pool(string Name);
name: web --- name: jobs
The snippet prints two documents, one for each Pool. If an object references itself, directly or through other objects, SerializeAll throws YamlException.
Unzip the example, then dotnet run.
Variations
Write a YAML file. Replace the Console.Write line with the following. It creates or overwrites pools.yaml with the same text shown above.
File.WriteAllText("pools.yaml", yaml);Related recipes
Write YAML from C# objects · Parse YAML into C# classes
The short answer
Call YamlSerializer.SerializeAll(pools) to serialize multiple Pool objects into one YAML string. The method writes one document per element, in order. Each document after the first starts with --- on its own line. Call Serialize(pools) instead if your reader expects a single document containing a sequence.
How do you put multiple YAML documents in one file?
Write the string returned by SerializeAll to the file. There’s no need to add your own delimiters. A YAML stream can start with ---; if your reader requires a marker before every document, prepend "---\n" to the nonempty string returned by SerializeAll. The first document in the example is the mapping name: web, not a list item. The same is true of name: jobs after the delimiter; it could be read independently of the first document. In a one-document sequence, by contrast, the top-level value is a list containing both mappings. This difference changes what type the consumer should read: a Pool per document or a collection of Pool in one document.
An empty input collection gives empty text, not a document containing []. If the consumer needs a document even when there are no pools, serialize the collection as one value with Serialize.
How do you read multiple YAML documents back into C# objects?
Use DeserializeAll<Pool> so OneYaml binds every document to Pool. First run the file-writing variation to create pools.yaml. Then add these lines above the record Pool declaration:
var restored = YamlSerializer.DeserializeAll<Pool>( File.ReadAllText("pools.yaml")); foreach (var pool in restored) Console.WriteLine(pool?.Name);
web jobs
The output shows that the separator is not part of either object. The property Name becomes name on write because the default naming policy is camel case. If you choose a different property naming policy, pass it to both calls so the YAML keys and the C# property names still match.