0

I use YamlDotnet and I have a YamlDocument. Now I want to convert it to his yaml text representation in memory but I don't see how to achieve that.

var yaml = new YamlDocument(new YamlMappingNode());
yaml.Add("one", "other")
var text = yaml.ToYamlText()

and I should get in text something like :

one: "other"

I tried zith Serializer class but with no success

Dragouf
  • 4,676
  • 4
  • 48
  • 55

1 Answers1

1

ok so I found the solution in unit test of the source code :

var yaml = new YamlDocument(new YamlMappingNode());
yaml.Add("one", "other");
var yamlStream = new YamlStream(yaml);
var buffer = new StringBuilder();
using (var writer = new StringWriter(buffer))
{
    yamlStream.Save(writer);
    yamlText = writer.ToString();
}

Anyway, I have now another problem, I need all my values to be surrounded by double quotes. In another application I was using a QuoteSurroundingEventEmitter : ChainedEventEmitter with an object graph selrialization. But with yamlStream.Save() I don't see how to implement this mecanism

Dragouf
  • 4,676
  • 4
  • 48
  • 55
  • Instead of adding a string, add a `YamlScalarNode` and set its Style property: `mapping.Add("one", new YamlScalarNode("other") { Style = ScalarStyle.DoubleQuoted });`. See a fully working example here - https://dotnetfiddle.net/YZlsc1 – Antoine Aubry Jun 15 '18 at 12:48
  • Yes it’s what I’ve finally done. Thanks a lot for your answer – Dragouf Jun 15 '18 at 12:55
  • @AntoineAubry quick question, when I use YamlStream.Save I got, as output result, strange random string before or after the key like this one : &1887939252. Any Idea why ? – Dragouf Jun 15 '18 at 13:36
  • 1
    ok again I found the reason why. Need to pass false as the second parameter of Save... – Dragouf Jun 15 '18 at 13:41
  • `YamlDocument` doesn't appear to have an `Add` method. Did something change? – Mike Christensen Nov 08 '19 at 02:35