You can use the DeserializerBuilder to configure a deserializer that only parses the section you’re interested in.
Make sure you have the YamlDotNet package installed. You can install it via NuGet package manager in Visual Studio or using the command line:
dotnet add package YamlDotNet
Define the C# classes that represent the structure of the YAML data you want to parse.
example:
public class ConfigOne { public string Name { get; set; } public string Stuff { get; set; } }
You will need to read the YAML content, extract the part you are interested in, and then deserialize it using YamlDotNet.
example:
using System; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; public class ConfigOne { public string Name { get; set; } public string Stuff { get; set; } } class Program { static void Main() { var yaml = @" config_one: name: foo stuff: value config_two: name: bar random: value"; // Parse the YAML document var deserializer = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build(); var yamlObject = deserializer.Deserialize>(yaml); // Extract the part you are interested in var configOnePart = yamlObject["config_one"].ToString(); // Deserialize the extracted part into the desired object var configOneDeserializer = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build(); var configOne = configOneDeserializer.Deserialize (configOnePart); // Output the result Console.WriteLine($"Name: {configOne.Name}, Stuff: {configOne.Stuff}"); } }
1. Read the YAML content: The YAML content is stored in a string variable yaml.
2. Deserialize the YAML into a dictionary: The first deserialization step converts the YAML into a dictionary where each top-level key (like config_one and config_two) maps to an object. This uses the Dictionary
3. Extract the specific part: After the YAML is deserialized into a dictionary, you can access the part of the YAML you are interested in (in this case, config_one). The value of config_one is still in YAML format and needs to be converted to a string.
4. Deserialize the specific part: Finally, you use another deserializer to convert the extracted YAML string into an instance of ConfigOne.
The NamingConvention is set to CamelCaseNamingConvention to match the C# property naming style.
The extracted config_one part is converted to a string using .ToString(). Depending on the deserializer, you may need to use Serialize method to get a proper YAML string if direct conversion does not work.