当我尝试使用c#读取Yaml文件时遇到一些问题,需要帮助才能完成此任务,我如何才能将这样的Yaml文件读入变量以便处理它们。
FileConfig:
sourceFolder: /home
destinationFolder: /home/billy/my-test-case
scenarios:
- name: first-scenario
alterations:
- tableExtension: ln
alterations:
- type: copy-line
sourceLineIndex: 0
destinationLineIndex: 0
- type: cell-change
sourceLineIndex: 0
columnName: FAKE_COL
newValue: NEW_Value1
- tableExtension: env
alterations:
- type: cell-change
sourceLineIndex: 0
columnName: ID
newValue: 10以下是我的代码
string text = System.IO.File.ReadAllText(@"test.yaml");
var deserializer = new Deserializer();
var result = deserializer.Deserialize<List<Hashtable>>(new StringReader(text));
/*foreach (var item in result)
{
Console.WriteLine("Item:");
Console.WriteLine(item.GetType());
foreach (DictionaryEntry entry in item)
{
Console.WriteLine("- {0} = {1}", entry.Key, entry.Value);
}
} */发布于 2020-05-27 22:05:00
最简单的方法是创建文档的C#模型。然后,您就可以使用Deserializer用文档中显示的数据填充该模型。文档的一种可能模型是:
public class MyModel
{
[YamlMember(Alias = "FileConfig", ApplyNamingConventions = false)]
public FileConfig FileConfig { get; set; }
}
public class FileConfig
{
public string SourceFolder { get; set; }
public string DestinationFolder { get; set; }
public List<Scenario> Scenarios { get; set; }
}
public class Scenario
{
public string Name { get; set; }
public List<Alteration> Alterations { get; set; }
}
public class Alteration
{
public string TableExtension { get; set; }
public List<TableAlteration> Alterations { get; set; }
}
public class TableAlteration
{
public string Type { get; set; }
public int SourceLineIndex { get; set; }
public int DestinationLineIndex { get; set; }
public string ColumnName { get; set; }
public string NewValue { get; set; }
}您可以反序列化到该模型,如下所示:
var deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
var obj = deserializer.Deserialize<MyModel>(yaml);您可以在此处运行以下代码:https://dotnetfiddle.net/SRABFM
当然,我在这里建议的模型是非常幼稚的,并且对您的领域模型有更多的了解,您肯定能够提出更好的模型。
https://stackoverflow.com/questions/62029377
复制相似问题