简体   繁体   中英

Save YamlStream from YamlDotNet Plugin to text file

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!

To people finding this without an answer, I found another answer useful . In short, everything is correct except the Save call. This excerpt from the other answer is what made the file actually contain the YAML:

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

I would suggest that you create a class representing the data structure you want to put into the YAML and serialise this class as shown in the other topic on YamlDotNet: How to serialize a custom class with YamlDotNet

Once done that you only need to create an object of your class and use the following code:

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

With the class defined deserialisation (should you ever perform one) is similarly simple:

YourClass yourObject = new YourClass();

using (StreamReader streamReader = new StreamReader("yourFile.yaml"))
{
    Deserializer deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().Build();
    yourObject = (ProcessingProfile)deserializer.Deserialize(streamReader, typeof(YourClass));
}
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();
    }
}
        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);

Im just a beginner but to save yaml file by your code:

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

you should add methods close() to close the StreamWriter. It works for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM