I want to merge two YAML files into one, in such a way that it would avoid duplicates and merge the attributes. As an example, having two yaml files as presented below:
yaml1:
first_name: "John"
last_name: "Smith"
enabled: false
roles:
- user
yaml2:
enabled: true
roles:
- user
- admin
I would expect the following result:
first_name: "John"
last_name: "Smith"
enabled: true
roles:
- user
- admin
So far I was able to do it converting YAML to JSON and using this example, however, I wanted to know a way using the C# YAML libraries (like yamldotnet and SharpYaml).
I have achieved it using Yamldotnet and then using the following algorithm:
Use the first yaml as base
Try to override the first yaml with the second one
2.1 If it's a new field add it
2.2 If the field exists and it isn't a collection, override it
2.3 If the field exists and it is a collection, merge the collection
2.3.1 If the new value is not a collection, add it to the collection
2.3.2 If the new value is a collection add each nonduplicated element to the collection. For this reason I use a
HashSet
, a collection that doesn't allow duplicated items.The code:
I hope this can help you :)