C#实现获取yaml文件中buildReleases父节点下所有的releaseID节点值(整型)以及其兄弟节点buildEnvironmentsbuildSystem的buildSystem子结点的值
时间: 2024-09-23 15:01:14 浏览: 31
在C#中,要从YAML文件中提取特定结构的数据,你可以使用一些开源库如`YamlDotNet`来解析YAML内容。首先,你需要添加YamlDotNet的NuGet包到你的项目中:
```xml
<PackageReference Include="YamlDotNet" Version="8.0.4" />
```
然后,你可以创建一个解析函数来读取并提取所需的值。假设YAML文件结构如下:
```yaml
buildReleases:
- releaseID: 1
buildEnvironments:
- buildSystem:
buildSystem: "GitLab CI"
- releaseID: 2
buildEnvironments:
- buildSystem:
buildSystem: "Jenkins"
```
你可以这样做:
```csharp
using System;
using YamlDotNet.Reading;
public static class YamlParser
{
public static void ExtractValues(string yamlFilePath)
{
var reader = new YamlStream();
if (!reader.LoadFromFile(yamlFilePath))
throw new Exception($"Failed to load YAML file: {yamlFilePath}");
var doc = reader.Documents[0];
foreach (var release in doc.RootNode.ChildrenNamed("buildReleases"))
{
int releaseId = (int)release.Children["releaseID"].Value;
string buildSystem = release.Children["buildEnvironments"][0].Children["buildSystem"]["buildSystem"].Value.ToString();
Console.WriteLine($"Release ID: {releaseId}, Build System: {buildSystem}");
}
}
}
```
要使用这个函数,传入你的YAML文件路径:
```csharp
string filePath = "path_to_your_yaml_file.yaml";
YamlParser.ExtractValues(filePath);
```
阅读全文