How do I parse only part of YAML using YamlDotNet?

Viewed 671

Suppose I have the following YAML:

config_one:
  name: foo
  stuff: value

config_two:
  name: bar
  random: value

I want to selectively parse config_one into an object and I want config_two to be ignored:

class ConfigOne
{
  public string Name {get;set;}
  public string Stuff {get;set;}
}

How can I do this? The documentation is pretty lacking, or at least, it uses a lot of terminology that doesn't make much sense to me, and thus I was not able to search for this functionality.

2 Answers

When building your deserializer, add IgnoreUnmatchedProperties():

var deserializer = new DeserializerBuilder()
    .WithNamingConvention(UnderscoredNamingConvention.Instance)
    .IgnoreUnmatchedProperties()
    .Build();

This "Instructs the deserializer to ignore unmatched properties instead of throwing an exception."
Git Source

With Cinchoo ETL - an open source library, you can load selective nodes using YamlPath with reader object.

Here is the working sample

string yaml = @"
config_one:
  name: foo
  stuff: value

config_two:
  name: bar
  random: value
";
using (var r = ChoYamlReader<ConfigOne>.LoadText(yaml)
    .WithYamlPath("config_one")
    )
{
    foreach (var rec in r)
        Console.WriteLine(rec.Dump());
}

Or one liner code

    Console.WriteLine(ChoYamlReader.DeserializeText<ConfigOne>(yaml, "config_one").FirstOrDefault().Dump());

Output:

-- ChoYamlReaderTest.Program+ConfigOne State --
        Name: foo
        Stuff: value

Sample fiddle: https://dotnetfiddle.net/oMzL3R

Disclaimer: I'm author of this library.

Related