Samuel
Samuel

Reputation: 113

Remove specific field of yaml file using YamlDotNet

I'm developing an application which reads a yaml file. Let's say the yaml file has the following content:

field1: 'test1'
field2: 'test2'
field3: 'test3'

So I want to remove only the filed2 as so the new yaml file would be:

field1: 'test1'
field3: 'test3'

How would I do it using the YamlDotNet library?

Upvotes: 0

Views: 828

Answers (1)

Roar S.
Roar S.

Reputation: 10904

Using YamlDotNet for for both deserializing and serializing may look like this:

const string yml = @"
    field1: 'test1'
    field2: 'test2'
    field3: 'test3'";

// deserialize yml into dictionary
var deserialized = new DeserializerBuilder()
    .Build()
    .Deserialize<Dictionary<string, string>>(yml);

// remove item with key = "field2"
deserialized.Remove("field2");

// serialize filtered dictionary to yml
var finalYml = new SerializerBuilder()
    .WithEventEmitter(nextEmitter => new QuoteSurroundingEventEmitter(nextEmitter))
    .Build()
    .Serialize(deserialized);

We'll need this class for surrounding values with '

public class QuoteSurroundingEventEmitter : ChainedEventEmitter
{
    private int _itemIndex;

    public QuoteSurroundingEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter) { }

    public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter)
    {
        if (eventInfo.Source.StaticType == typeof(object) && _itemIndex++ % 2 == 1)
        {
            eventInfo.Style = ScalarStyle.SingleQuoted;
        }
        base.Emit(eventInfo, emitter);
    }
}

Code is tested in a Core 5 console app using YamlDotNet 11.2.1.

Upvotes: 1

Related Questions