Remove declaration from XML

Description

Out of the box, .NET XML serialization is loaded with garbage that I personally never want. It’s one of the reasons I use JSON instead of XML whenever possible.

But one quick way to remove the junk, assuming you’re dealing with simple data, and don’t care about things like encoding or namespaces or whatever, is to just apply a few settings.

Given the following out-of-the-box code:

var foo = new Foo { Name = "John Doe", Age = 34 };
using (var writer = XmlWriter.Create(Console.Out)) {
    new XmlSerializer(typeof (Foo)).Serialize(writer, foo);
}

The console will see the following (aside from the indentation):

<?xml version="1.0" encoding="Codepage - 437"?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Name>John Doe</Name>
    <Age>34</Age>
</Foo>

Add a little bit of configuration to the code, and you get something much nicer:

var ns = new XmlSerializerNamespaces(); ns.Add("", "");
var settings = new XmlWriterSettings { OmitXmlDeclaration = true };
using (var writer = XmlWriter.Create(Console.Out, settings)) {
    new XmlSerializer(typeof (Foo)).Serialize(writer, foo, ns); 
}
<Foo>
  <Name>John Doe</Name>
  <Age>34</Age>
</Foo>