将 YamlDotNet 插件中的 YamlStream 保存到文本文件

Save YamlStream from YamlDotNet Plugin to text file

我需要在 C# 应用程序中为 ROS 节点构建一个 YAML 配置文件。基本上,用户指定参数值,我获取这些值来编写 YAML 文件。

我在@Antoine Aubry 提供的出色 YamlDotNet 插件的帮助下在 MonoDevelop 上进行开发。但是,从这个问题开始:,我找不到将 YAML 文档保存到简单文本文件的方法,而不是在控制台中输出它。

我一直在研究 StreamWriter、TextWriter、Byte Converter 以及许多我在这里有点迷路的东西。 我正在使用这个示例代码,在这个 fiddle https://dotnetfiddle.net/0raqgN

  var address = new YamlMappingNode(
        new YamlScalarNode("street"), new YamlScalarNode("123 Tornado Alley\nSuite 16") { Style = YamlDotNet.Core.ScalarStyle.Literal },
        new YamlScalarNode("city"), new YamlScalarNode("East Westville"),
        new YamlScalarNode("state"), new YamlScalarNode("KS")
    ) { Anchor = "main-address" };

  var stream = new YamlStream(
        new YamlDocument(
            new YamlMappingNode(
                new YamlScalarNode("repeipt"), new YamlScalarNode("Oz-Ware Purchase Invoice"),
                new YamlScalarNode("date"), new YamlScalarNode("2007-08-06"),
                new YamlScalarNode("customer"), new YamlMappingNode(
                    new YamlScalarNode("given"), new YamlScalarNode("Dorothy"),
                    new YamlScalarNode("family"), new YamlScalarNode("Gale")
                ),
                new YamlScalarNode("items"), new YamlSequenceNode(
                    new YamlMappingNode(
                        new YamlScalarNode("part_no"), new YamlScalarNode("A4786"),
                        new YamlScalarNode("descrip"), new YamlScalarNode("Water Bucket (Filled)"),
                        new YamlScalarNode("price"), new YamlScalarNode("1.47"),
                        new YamlScalarNode("quantity"), new YamlScalarNode("4")
                    ),
                    new YamlMappingNode(
                        new YamlScalarNode("part_no"), new YamlScalarNode("E1628"),
                        new YamlScalarNode("descrip"), new YamlScalarNode("High Heeled \"Ruby\" Slippers"),
                        new YamlScalarNode("price"), new YamlScalarNode("100.27"),
                        new YamlScalarNode("quantity"), new YamlScalarNode("1")
                    )
                ),
                new YamlScalarNode("bill-to"), address,
                new YamlScalarNode("ship-to"), address,
                new YamlScalarNode("specialDelivery"), new YamlScalarNode("Follow the Yellow Brick\nRoad to the Emerald City.\nPay no attention to the\nman behind the curtain.") { Style = YamlDotNet.Core.ScalarStyle.Literal }
            )
        )
    );

我最后尝试的是这个:

StreamWriter sw = new StreamWriter (@"/home/guillaume/test_yaml.yaml");
stream.Save (sw);

但是文件 test_yaml.yaml 每次都该死的仍然是空的(0 个八位字节),而我希望它看起来像这样:

  repeipt: Oz-Ware Purchase Invoice
  date: 2007-08-06
  customer:
    given: Dorothy
    family: Gale
  items:
  - part_no: A4786
    descrip: Water Bucket (Filled)
    price: 1.47
    quantity: 4
  - part_no: E1628
    descrip: High Heeled "Ruby" Slippers
    price: 100.27
    quantity: 1
  bill-to: &main-address
    street: |-
      123 Tornado Alley
      Suite 16
    city: East Westville
    state: KS
  ship-to: *main-address
  specialDelivery: |-
    Follow the Yellow Brick
    Road to the Emerald City.
    Pay no attention to the
    man behind the curtain.
  ...

抱歉,如果这看起来像一个菜鸟问题!

对于找不到答案的人,我找到了 。简而言之,除了 Save 调用之外,一切都是正确的。另一个答案的摘录是使文件实际包含 YAML 的原因:

using (TextWriter writer = File.CreateText("C:\temp\some-file.yaml")) {
    yaml.Save(writer, false);
}
        var stream = new YamlStream();
        stream.Add(YamlDoc);

        string output;
        var sb = new StringBuilder();

        using (var writer = new StringWriter(sb))
        {
            stream.Save(writer, false);
            output = sb.ToString();
        }

        Console.WriteLine(output);

我建议您创建一个 class 来表示您要放入 YAML 中的数据结构并序列化此 class,如 YamlDotNet 上的其他主题所示:

完成后,您只需创建 class 的对象并使用以下代码:

YourClass yourObject = new YourClass(param1, param2, param3);
using (StreamWriter streamWriter = new StreamWriter("yourFile.yaml")))
{
    Serializer serializer = new SerializerBuilder().Build();
    serializer.Serialize(streamWriter, yourObject);
}

使用 class 定义的反序列化(您是否应该执行反序列化)同样简单:

YourClass yourObject = new YourClass();

using (StreamReader streamReader = new StreamReader("yourFile.yaml"))
{
    Deserializer deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().Build();
    yourObject = (ProcessingProfile)deserializer.Deserialize(streamReader, typeof(YourClass));
}

我只是一个初学者,但要通过您的代码保存 yaml 文件:

StreamWriter sw = new StreamWriter (@"/home/guillaume/test_yaml.yaml");
stream.Save (sw);
sw.Close();

您应该添加方法 close() 来关闭 StreamWriter。对我有用

using YamlDotNet.RepresentationModel;
using YamlDotNet.Serialization;

public static void DumpAsYaml(object data, string fileName)
{
    //Console.WriteLine("***Dumping Object Using Yaml Serializer***");
    var stringBuilder = new StringBuilder();
    var serializer = new Serializer();
    stringBuilder.AppendLine(serializer.Serialize(data));
    Console.WriteLine($"Now writing {fileName}");

    var stream = new FileStream(fileName, FileMode.OpenOrCreate);
    using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
    {
        writer.Write(stringBuilder);
        writer.Close();
    }
}