C#获取yaml文件中父节点buildRelease下所有子节点为releaseID的值以及兄弟节点buildEnvironment下所有子节点为buildSystem,
时间: 2024-09-24 21:04:15 浏览: 36
在C#中,如果你需要从YAML文件中获取特定结构的数据,通常可以使用第三方库如`YamlDotNet`。首先,你需要安装这个库(如果尚未安装):
```bash
Install-Package YamlDotNet
```
然后,你可以创建一个解析YAML文档并访问所需数据的类。下面是一个基本示例,假设你的YAML文件结构类似这样:
```yaml
build:
release:
- releaseID: value1
otherProperties: ...
- releaseID: value2
otherProperties: ...
buildEnvironment:
buildSystem:
- name: system2
```
你可以使用`YamlNode`类和递归方法来遍历并查找所需的值:
```csharp
using YamlDotNet.Reading;
using YamlDotNet.Serialization;
public class YamlHelper
{
public static string[] GetReleaseIdsAndBuildSystems(string yamlContent)
{
var loader = new SafeYamlLoader(yamlContent);
var rootNode = loader.Load();
List<string> releaseIds = new List<string>();
List<string> buildSystems = new List<string>();
VisitNodeRecursively(rootNode, ref releaseIds, ref buildSystems);
return releaseIds.ToArray(), buildSystems.ToArray();
}
private static void VisitNodeRecursively(YamlNode node, ref List<string> releaseIds, ref List<string> buildSystems)
{
if (node is MappingNode mapping && mapping.Children.Contains("release"))
{
foreach (var child in mapping.Children["release"])
{
if (child is ScalarNode scalar && scalar.Value == "releaseID")
releaseIds.Add(scalar.Value);
}
}
if (node is MappingNode environment && environment.Children.Contains("buildSystem"))
{
foreach (var child in environment.Children["buildSystem"])
{
if (child is ScalarNode buildSystemScalar && buildSystemScalar.Value == "name")
buildSystems.Add(buildSystemScalar.Value);
}
}
foreach (var child in node.Children)
VisitNodeRecursively(child, ref releaseIds, ref buildSystems);
}
}
```
要使用这个帮助类,传入你的YAML内容:
```csharp
string yamlContent = File.ReadAllText("your_yaml_file.yaml");
string[] result = YamlHelper.GetReleaseIdsAndBuildSystems(yamlContent);
```
阅读全文