Remove declaration and namespaces from XML serializer

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="" xmlns:xsd="">
    <Name>John Doe</Name>

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); 
  <Name>John Doe</Name>


Popular posts from this blog

DotNet CLI

Switch Expressions