.NetFramework4.8实现读取yaml文件中父节点buildReleases下的releaseID节点值以及buildEnvironments下buildSystem的节点值
时间: 2024-09-24 08:05:31 浏览: 30
在.NET Framework 4.8中,你可以使用`System.IO.Pipelines.Text`库配合第三方库如`YamlDotNet`来解析YAML文件。首先,需要安装`YamlDotNet`库,可以通过NuGet包管理器添加。然后,以下是读取指定结构YAML文件内容的一个示例:
```csharp
using System;
using System.IO.Pipelines.Text;
using YamlDotNet.Core;
using YamlDotNet.Readers;
class Program
{
static void Main(string[] args)
{
string yamlFilePath = "path_to_your_yaml_file.yaml"; // 替换为实际文件路径
using (FileStream stream = File.OpenRead(yamlFilePath))
using (TextReader reader = new StreamReader(stream))
{
YamlDocument deserializer = new YamlDocument(new SingleLineParser(reader));
if (deserializer.Documents.Count > 0)
{
var doc = deserializer.Documents[0];
var buildReleases = doc.RootNode?.GetValue<Dictionary<string, object>>("buildReleases");
if (buildReleases != null && buildReleases.TryGetValue("releaseID", out var releaseId))
Console.WriteLine($"Release ID: {releaseId}");
var buildEnvironments = doc.RootNode?.GetValue<Dictionary<string, object>>("buildEnvironments")?.FirstOrDefault()?.GetValue<Dictionary<string, object>>("buildSystem");
if (buildEnvironments != null && buildEnvironments.TryGetValue("name", out var buildSystemName))
Console.WriteLine($"Build System Name: {buildSystemName}");
}
else
{
Console.WriteLine("No documents found in the YAML file.");
}
}
}
}
```
这段代码首先打开并读取YAML文件,然后使用`YamlDocument`类解析文件内容。接着,它尝试获取`buildReleases`和`buildEnvironments`下的相应节点,并打印出它们的值。
注意,上述代码假设`releaseID`和`buildSystem`都是字符串类型的。如果它们有不同的数据类型,你需要修改`GetValue`后的类型提示和相应的处理逻辑。
阅读全文