C#实现从yaml文件中获取某个根节点buildReleases下父节点buildEnvironments的子结点buildSystem的节点值
时间: 2024-11-09 22:25:34 浏览: 5
解决pycharm编辑区显示yaml文件层级结构遇中文乱码问题
在C#中,你可以使用`YAML.NET`库来解析YAML文件并获取特定节点的值。首先,需要安装`YAMLDotNet`库。下面是一个示例,展示如何从给定的YAML字符串中获取指定路径的值:
```csharp
using System;
using YAML Ain't markup language;
using YAMLDotNet.Serialization;
public class BuildNode
{
public string buildReleases { get; set; }
public BuildEnvironmentNode buildEnvironments { get; set; }
public BuildSystemNode buildSystem { get; set; }
}
public class BuildEnvironmentNode
{
public BuildSystemNode buildSystem { get; set; }
// 其他属性...
}
public class BuildSystemNode
{
public string value { get; set; } // 这里假设value是你想要的键值
}
public static string GetValueFromYaml(string yamlContent, string path)
{
var deserializer = new DeserializerBuilder().Build();
BuildNode root = null;
try
{
root = deserializer.Deserialize<BuildNode>(yamlContent);
}
catch (YamlException e)
{
throw new ArgumentException("Invalid YAML content", e);
}
string result = "";
var parts = path.Split('.');
foreach (string part in parts)
{
if (root != null && root.GetType().GetProperty(part) != null)
{
root = (BuildNode)(root.GetType().GetProperty(part).GetValue(root));
}
else
{
result = "Path not found";
break;
}
}
if (root != null && root.buildSystem != null && root.buildSystem.value != null)
{
result = root.buildSystem.value;
}
return result;
}
```
在这个例子中,`path`应该是类似"buildReleases.buildEnvironments.buildSystem.value"的形式,表示你想要获取的完整路径。
阅读全文