C#获取yaml文件中父节点buildRelease下所有子节点为releaseID的值以及releaseID的兄弟节点buildEnvironment下所有子节点为buildSystem的值
时间: 2024-09-23 18:05:47 浏览: 40
wp-yaml:用于将 YAML 文件转换为 Wordpress XML 的节点实用程序
在C#中,你可以使用`YamlDotNet`库来解析YAML文件。首先,你需要安装这个NuGet包。以下是处理这种情况的一种基本方法:
```csharp
using YamlDotNet;
using YamlDotNet.Readers;
using YamlDotNet.Serialization;
// 假设有一个名为Config.yaml的文件内容如下:
// buildRelease:
// - releaseID: value1
// - releaseID: value2
// buildEnvironment:
// - buildSystem: valueA
// - buildSystem: valueB
public class Config
{
public BuildRelease[] BuildRelease { get; set; }
public BuildEnvironment[] BuildEnvironment { get; set; }
}
public class BuildRelease
{
public string releaseID { get; set; }
}
public class BuildEnvironment
{
public string buildSystem { get; set; }
}
// 加载并解析YAML文件
string yamlText = File.ReadAllText("Config.yaml");
var parser = new YamlParser();
var deserializer = new DeserializerBuilder().Build();
Config config = null;
try
{
config = deserializer.Deserialize<Config>(new StringReader(yamlText));
}
catch (DeserializationException ex)
{
Console.WriteLine($"Error parsing YAML: {ex.Message}");
}
// 获取所需数据
foreach (var release in config.BuildRelease)
{
Console.WriteLine($"releaseID: {release.releaseID}");
}
foreach (var env in config.BuildEnvironment)
{
Console.WriteLine($"buildSystem: {env.buildSystem}");
}
阅读全文