How to Serialize objects to XML without namespace and declaration

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!
Please leave a “Like” and/or use the share buttons, if you found this guide usefull

Advertisements
3 comments
  1. Very good, this is less effort than what I found in other hints, that usually required deriving from XmlSerializer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Sitecore tackled

Small posts about Sitecore and solutions

Cooking with Sitecore

Diary of my experience working on great CMS called Sitecore

Visions In Code

Never look back

Cook 4 Passion

Food food fooooood. We love fooooooooood !!!

Eldblom

Sitecore, Digital Marketing, Work, Life and so on...

SitecoreJunkie.com

Down the DLL Rabbit Hole

frontendrush

Arash Sarfehjou

DotNetCoder.dk

.NET code and tweaks

.NET code and tweaks

The grumpy coder.

.NET code and tweaks

Alan Coates - Sitecore/.NET blog

Pushing Sitecore to the limits and beyond

Patrick Delancy

i write code

Laub plus Co

.NET code and tweaks

iStern Blog

A simple Code Blog

Brian Pedersen's Sitecore and .NET Blog

Sitecore, C#, ASP.NET for developers

%d bloggers like this: