Recursive AI

Read duplicate YAML key values in C#

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

Terminal
dotnet add package OneYaml

Targets .NET 8 and .NET 10.

C#
using OneYaml;
using var doc = YamlDocument.Parse(
    "host: primary\nhost: backup\n",
    new() { AllowDuplicateKeys = true });
foreach (var (key, value) in doc.Root.Entries)
    if (key.GetValue<string>() == "host")
        Console.WriteLine(
            value.GetValue<string>());

Prints both values in file order:

Text
primary
backup

Unzip the example, then dotnet run.

The full program

The program adds an unrelated port setting to the inline YAML and prints the source line of each host key.

C#
using OneYaml;
 
var options = new YamlDocumentOptions
{
    AllowDuplicateKeys = true
};
using var doc = YamlDocument.Parse("""
    host: primary
    port: 8080
    host: backup
    """, options);
 
foreach (var (key, value) in doc.Root.Entries)
{
    if (key.TryGetValue<string>(out var name) && name == "host")
    {
        Console.WriteLine($"Line {key.Position.Line}: {value.GetValue<string>()}");
    }
}
Text
Line 1: primary
Line 3: backup

Without AllowDuplicateKeys, parsing throws a YamlException with category DuplicateKey.

Variations

If both hosts are meant to stay, put them under one key as a YAML sequence. This is the value list after cleanup:

YAML
hosts: [primary, backup]
C#
using OneYaml;
 
using var doc = YamlDocument.Parse("hosts: [primary, backup]");
foreach (var host in doc.Root["hosts"].Items)
    Console.WriteLine(host.GetValue<string>());
Text
primary
backup

The short answer

Parse with YamlDocumentOptions.AllowDuplicateKeys = true, then walk Entries on the mapping that contains the repeated key. Each matching entry gives you a value and its own key node. The full program reports the key’s source line, so you can locate both definitions even when they are far apart.

Does YAML allow duplicate keys?

The YAML specification requires unique keys within each mapping. Two sibling host keys conflict; a host key under primary and another under backup are in separate mappings and do not conflict. OneYaml’s opt-in allows you to open an invalid mapping to inspect it. It doesn’t make repeated keys valid in the file you ship.

The editing guide notes that OneYaml compares parsed keys after resolving their types. For example, 1 and 0x1 both denote the integer one, so they conflict. The quoted "1" is a string and does not conflict with the integer. The recipe filters for the string host, not arbitrary numeric or structured keys.

Can a C# dictionary keep both values for a duplicate key?

A Dictionary<TKey, TValue> stores one value per key. It can store a list as that value, but collecting the values into a list is a decision you make after reading the entries. OneYaml won’t make that decision for you: when duplicates are allowed, a pointer or indexer that matches more than one entry throws RefusedAmbiguous rather than selecting the first or last.

Use source order and line numbers to review the conflicting entries. If one is obsolete, remove it. If the application is meant to accept more than one value, move the entries into a sequence and make sure the application expects a list there. Then read the corrected file with duplicate-key handling left at its default so the next accidental repeat surfaces as an error.

All oneyaml C# recipes