YamlDotNet
YamlDotNet copied to clipboard
Add new line between items
Looking for a way of adding new line per every new line
var yamlSerializer = new SerializerBuilder()
.AddNewLinePerEveryNewItem() // smth like this or similar API
.Build()
Before:
first1:
hello: true
world: true
there:
a: true
b: true
c: true
first2:
a: false
After:
first1:
hello: true
world: true
there:
a: true
b: true
c: true
first2:
a: false
With a recent addition this is a lot easier, you can wrap the emitter with a custom one and expose the textwriter. From there you have a custom typeconverter that adds the empty line where ever you want them.
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
var serializer = new SerializerBuilder().WithTypeConverter(new TestConverter()).Build();
var stringWriter = new StringWriter();
var emitter = new SillyEmitter(stringWriter);
serializer.Serialize(emitter, new Outer());
Console.WriteLine(stringWriter.ToString());
class Outer
{
public First1 First1 = new First1();
public There There = new There();
public First2 First2 = new First2();
}
class First1
{
public bool Hello = true;
public bool World = true;
}
class There {
public bool A = true;
public bool B = true;
public bool C = true;
}
class First2
{
public bool A = true;
}
class TestConverter : IYamlTypeConverter
{
public bool Accepts(Type type) => type == typeof(Outer);
public object? ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) => throw new NotImplementedException();
public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer)
{
var v = (Outer)value!;
((SillyEmitter)emitter).Writer.WriteLine();
emitter.Emit(new MappingStart());
emitter.Emit(new Scalar("first1"));
serializer(v.First1);
((SillyEmitter)emitter).Writer.WriteLine();
emitter.Emit(new Scalar("there"));
serializer(v.There);
((SillyEmitter)emitter).Writer.WriteLine();
emitter.Emit(new Scalar("first2"));
serializer(v.First2);
emitter.Emit(new MappingEnd());
}
}
class SillyEmitter : Emitter
{
public TextWriter Writer { get; }
public SillyEmitter(TextWriter output) : base(output)
{
Writer = output;
}
public SillyEmitter(TextWriter output, int bestIndent) : base(output, bestIndent)
{
Writer = output;
}
public SillyEmitter(TextWriter output, EmitterSettings settings) : base(output, settings)
{
Writer = output;
}
public SillyEmitter(TextWriter output, int bestIndent, int bestWidth) : base(output, bestIndent, bestWidth)
{
Writer = output;
}
public SillyEmitter(TextWriter output, int bestIndent, int bestWidth, bool isCanonical) : base(output, bestIndent, bestWidth, isCanonical)
{
Writer = output;
}
}
Results in
first1:
Hello: true
World: true
there:
A: true
B: true
C: true
first2:
A: true
I'm going to close this since an answer has been provided.