Posts Tagged ‘XmlSerializer’


Recently I had to recreate an old service module from an old website, which outputted XML. There was a requirement to meet a certain format, which was without xml namespaces (XMLNS) and declarations.

Our project team decided to use object serialization and I quickly ran into the problem that the .Net serializers likes to output namespaces and declarations. There is however a way to avoid this

Here is how I did it:

 public string ToXml()
{
   //this avoids xml document declaration
   XmlWriterSettings settings = new XmlWriterSettings() {
                   Indent = false, OmitXmlDeclaration = true };
   var stream = new MemoryStream();
   using (XmlWriter xw = XmlWriter.Create(stream, settings))
   {
      //this avoids xml namespace declaration
      XmlSerializerNamespaces ns = new XmlSerializerNamespaces(
                         new[] { XmlQualifiedName.Empty });
      XmlSerializer x = new XmlSerializer(GetType(), "");
      x.Serialize(xw, this, ns);
   }
   return Encoding.UTF8.GetString(stream.ToArray());
 }

Enjoy!