2

I need to construct a YAML configuration file for a ROS node, inside a C# application. Basically, users specifies parameters values, and I fetch those values to write the YAML file.

I'm developing on MonoDevelop with help of the great YamlDotNet plugin by @Antoine Aubry. However, starting from this question : Build a Yaml document dynamically from c#, I cannot find a way to save the YAML document to a simple text file, instead of outputting it in the console.

I've been looking into StreamWriter, TextWriter, Byte Converter and so many things that I'm a little lost here. I'm using this example code, in this 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 }
            )
        )
    );

The last thing I tried was this :

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

But the file test_yaml.yaml remains empty (0 octets) every damn time, whereas I want it to look like this :

  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.
  ...

Sorry if this looks like a noob question!

4

5 回答 5

1

我建议您创建一个表示要放入 YAML 的数据结构的类,并序列化该类,如 YamlDotNet 上的另一个主题所示:如何使用 YamlDotNet 序列化自定义类

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

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

使用类定义的反序列化(你应该执行一个)同样简单:

YourClass yourObject = new YourClass();

using (StreamReader streamReader = new StreamReader("yourFile.yaml"))
{
    Deserializer deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().Build();
    yourObject = (ProcessingProfile)deserializer.Deserialize(streamReader, typeof(YourClass));
}
于 2018-07-04T10:07:04.710 回答
1

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

using (TextWriter writer = File.CreateText("C:\\temp\\some-file.yaml")) {
    yaml.Save(writer, false);
}
于 2018-01-06T22:30:30.400 回答
1
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();
    }
}
于 2021-01-29T10:18:29.033 回答
0
        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);
于 2018-07-04T02:25:49.137 回答
0

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

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

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

于 2020-08-31T04:47:01.253 回答