【问题标题】:Reading Yamldotnet with c#用 c# 读取 Yamldotnet
【发布时间】:2023-03-22 09:17:01
【问题描述】:

当我尝试使用 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);
    }
}    */



【问题讨论】:

  • 欢迎来到 Stack Overflow。听起来您已经开始了 - 所以请向我们展示您现有的代码,以及您遇到的问题。
  • @JonSkeet 我发现这段代码使用 hashtable 和 DictionnaryEntry 它可以解决 Lists 的问题。但就我而言,我试图找到一个很好的文档来简化它,但没有找到
  • Yaml Dotnet wiki 包含您需要的所有信息,包括展示如何反序列化的示例。 github.com/aaubry/YamlDotNet/wiki/…

标签: c# .net .net-core yaml yamldotnet


【解决方案1】:

最简单的方法是创建文档的 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

当然,我在这里建议的模型非常幼稚,并且对您的领域模型有更多的了解,您一定能够想出一个更好的模型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-15
    • 2015-12-20
    • 2022-01-02
    • 2017-10-01
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多