Fluent XML writer

Posted by Joe Enos on May 20, 2021 · 3 mins read

Writing XML in .NET is not too terrible, but it sometimes is a bit tricky and lengthy.

A few years ago, I put this library together to write XML easily, using fluent techniques.

static void Main(string[] args) {
FluentXmlWriter.Start("root")
.Simple("First")
.Simple("Second").Attr("a", "b")
.Complex("Arr")
.ManySimple(
SimpleElement.Create("Arr1").Attr("key1", "val1"),
SimpleElement.Create("Arr2").Attr("key2", "val2")
).EndElem()
.Complex("Third").Text("My Text").EndElem()
.Complex("Fourth").CData("Hello there!").EndElem()
.Comment("A comment!")
.OutputToString(Console.WriteLine);
}

This produces the following output:

<root>
<First />
<Second a="b" />
<Arr>
<Arr1 key1="val1" />
<Arr2 key2="val2" />
</Arr>
<Third>My Text</Third>
<Fourth><![CDATA[Hello there!]]></Fourth>
<!--A comment!-->
</root>
Download on Github