Serializing without the namespace (xmlns, xmlns:xsd, xmlns:xsi)
posted on Monday, August 22, 2005 by bobby @ 10:48 pm
I've always been a fan of serialization, but that's not to say it can't be frustrating. When serializing complex objects, you have to load your constructs up with xml attributes to let the serializer know how to build your XML. If you forget, expect a nice fatty exception IN YO FACE!

Another significant annoyance is when the default XmlSerializer adds xmlns attributes such as:

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

and

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

I'm pretty sure these are by default - which I don't have a problem with... until you can't deserialize them back into objects because of them - weak. Rather than try to figure out why it won't deserialize, I decided to just remove them - since I won't personally use them and they are taking up ever-so precious bytes.

Didn't think it'd be so hard to dig up instructions on how to get rid, but it was, thus the reason for this post. Maybe it'll save you an hour or two.

To remove these namespaces from your XML, add your own XmlSerializerNamespaces object and tie it in when serializing, like this:

Copy code to clipboard in IE or select code for Firefox
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns);


That should remove the xmlns:xxx crap from your output. However, it won't remove
<?xml version="1.0" encoding="utf-8"?>

Innit??

CommentsComments
posted on Sunday, January 15, 2006  by Nathan Palmer @ 2:25 PM

Hey.. I was having the same problem as you. Luckily I found a post that solved my problem. Basically you have to create a custom class that sets the WriteStartDocument to null. Here is the class.
Copy code to clipboard in IE or select code for Firefox
public class XmlTextWriterFormattedNoDeclaration : System.Xml.XmlTextWriter
{
        public XmlTextWriterFormattedNoDeclaration(System.IO.TextWriter w)
            : base(w)
        {
            Formatting = System.Xml.Formatting.Indented;
        }

        public override void WriteStartDocument() { } // suppress
}


Then you can serialize like this.
Copy code to clipboard in IE or select code for Firefox
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");

XmlSerializer serializer = new XmlSerializer(typeof(object));
StringWriter sw = new StringWriter();
XmlWriter writer = new XmlTextWriterFormattedNoDeclaration(sw);
serializer.Serialize(writer, this, ns);


You are left with just your bare xml. It's great.

Nathan
posted on Friday, February 23, 2007  by Thomas Lunsford @ 12:45 PM

Excellent! Thank you.
posted on Wednesday, March 14, 2007  by Anonymous @ 10:00 AM

Thanks for saving me time.

To remove the <?xml version="1.0" encoding="utf-8"?> crap use XmlWriterSettings. Like this:

XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true; // Remove the <?xml version="1.0" encoding="utf-8"?>

XmlWriter writer = XmlWriter.Create( "output_file_name.xml", settings );
posted on Friday, March 23, 2007  by ee @ 2:10 PM

Thanks for the tip! And the comments from Anonymous!

I have summarized these suggestions in a generics function on the DevFuel blog for those of you who are interested:
http://devfuel.blogspot.com/2007/03/xmlserializer-now-with-less-xmlnsxsi.html

You also have won yourself an RSS subscriber. *chuckle* C# Shiznit indeed.
posted on Wednesday, April 18, 2007  by Anonymous @ 9:51 AM

Great post - thanks.

Now, anyone have a suggestion on how to employ this technique when you aren't explicitly instantiating the XmlSerializer, such as when returning data from a WebMethod?
posted on Wednesday, May 16, 2007  by Anonymous @ 11:45 AM

Groovy add-comment effect....now why can't I select the text in the comments! So annoying. I want to click that link and now I have to parse out all the text....
posted on Wednesday, May 16, 2007  by bobby @ 11:52 AM

You should be able to select text - I had no problem in Firefox, but I see what you mean in IE. I didn't do anything specific to prevent selecting text.
posted on Wednesday, May 16, 2007  by Anonymous @ 11:55 AM

I guess I see the "XHTML 1.0 Strict; tuned for Mozilla-powered browsers" because-IE7-cannot-handle-it notice at the bottom...
posted on Monday, May 28, 2007  by Anonymous @ 4:19 PM

This almost works. but its lame. it causes "q1:" to go in front of every single element, including the root.

<?xml version="1.0" encoding="utf-8" ?>
<q1:Person xmlns:q1="http://myNamespace">
<q1:name>...

WFT? I have no idea where this magic crap is coming from. Thoughts?
posted on Thursday, June 21, 2007  by Nitin @ 2:59 PM

Thanks the XmlSerializerNamespaces saved me lots of time, i appreciate it
Good Work!
posted on Sunday, June 24, 2007  by citykid @ 3:30 AM

thanks! i am trying along the line, but finding your post brought me faster there.

(i have the same selection problem on this website with ie6)

have fun
posted on Tuesday, July 03, 2007  by Mark @ 9:46 AM

Thanks! You should post this on something like www.codeproject.com - it took me ages to find this because it is pretty hard to search for. Good job again :-)
posted on Friday, September 07, 2007  by Anonymous @ 2:03 PM

Does anyone know how you can maintain the comments that are in your XML document when you use serialization/deserialization. After I use it, all of my comments are gone.
posted on Tuesday, September 18, 2007  by Ramu @ 1:33 AM

Thanks a lot (one more, but there are never enough) !
posted on Tuesday, September 25, 2007  by Anonymous @ 7:25 AM

We seem to have a need to do just the opposit: output the name space of the object when serializing it.

We have something as follows from serialization. It fails in xmlValidating. but when I add "xmlns="http://myNS" to the root (MyObject), the validator is happy and the de-serializer crashes.
So I guess if the serializer can output the namespace of "xmlns="http://myNS" we could make both validator and de-serializer happy. But have not found out how to do that using declaretive or some generic form. without hard code anything. e.g let the serializer pick up the name space of the class and write to the root node....

<MyObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyCollection xmlns="http://myNS">
<MyEle ...>
....
</MyEle>
</MyCollection>
</MyObject>
posted on Monday, November 12, 2007  by Emma @ 4:27 AM

Thanks this just saved me a ton of work!
posted on Monday, January 14, 2008  by Reeve @ 7:42 PM

<?xml version="1.0" encoding="utf-8"?>

could be removed by adding a XMLWriterSettings

// removing XML declaration, the default is false
System.Xml.XmlWriterSettings xmlwtSettings = new System.Xml.XmlWriterSettings();
xmlwtSettings.OmitXmlDeclaration = true;

// create a XML writer using the settings
System.Xml.XmlWriter xmlwt = System.Xml.XmlWriter.Create(new MemoryStream(), xmlwtSettings);

xmlsz.Serialize(xmlwt, someObj);
posted on Tuesday, February 12, 2008  by Andrew @ 4:54 PM

Thanks dawg.... er... uh ... I mean G. I always need help removing Microsoft's help.
posted on Wednesday, March 05, 2008  by ktmt @ 3:08 PM

Excellent post! Cleaned up my Xml just the way I wanted and, like everyone else, saved me a bunch of time. thanks!
posted on Thursday, April 03, 2008  by Anonymous @ 3:18 AM

Very helpful, saved me lots of time!
posted on Tuesday, May 13, 2008  by Ram @ 9:14 AM

Hi,

your post has been very helpful.

I am createing a namespace like this.

<StudentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

But, I am getting <xsi:StudentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema
-instance">

I would like to remove the <xsi:

Any help will be greatly apprecaited.

Thx,
Ram
posted on Thursday, May 29, 2008  by Mário Rodrigues @ 9:03 AM

Hi Ram!
I've solved that issue by setting a namespace to my class and using the defaultNameSpace on the XmlSerialier like in this function I've made:

Public Sub SaveXML()
Dim ns As New XmlSerializerNamespaces
Dim sets As New Xml.XmlWriterSettings
ns.Add("", "myDefinitions")
Dim writer As New XmlSerializer(GetType(myClassToSerialize), defaultNamespace:="myDefinitions")
Dim file As New StreamWriter("c:\teste.xml")
writer.Serialize(file, Me, ns)
file.Close()
End Sub


It's in VB but I hope it helps somehow!
Best Regards,
Mário Rodrigues
posted on Wednesday, June 18, 2008  by Anonymous @ 9:01 AM

So, here is a nice function which pulls all these ideas together


public static string </span>ObjectToXmlString(object obj)
{
if (obj != null)
{
// Make this idiotic thing
XmlWriterSettings wset = new XmlWriterSettings();
// set this so that we don't pollute our XML
wset.OmitXmlDeclaration = true;
// Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value so we don't pollute our XML
ns.Add("", "");
// create a XML writer using the XmlWriterSettings object so that it won't pollute our XML
StringBuilder sb = new StringBuilder();
XmlWriter xmlw = XmlWriter.Create(sb, wset);
// Make the serializer
XmlSerializer xmls = new XmlSerializer(obj.GetType());
// tell the serializer to use our *empty* namespace so it won't pollute our XML
xmls.Serialize(xmlw, obj, ns);
// Make sure the serialize function is finished
// (WTF!!! - where does it indicate it's potentially asynchronous - More MS Nonsense)
xmlw.Flush();
// we're Done - Hurray !
return sb.ToString(); ;
}
else
return "";
}
posted on Thursday, July 03, 2008  by Anonymous @ 5:49 AM

this much of coding is not required. just add few attribute over class you use to serialize without name space. here is sample code.

[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public class SummaryData
{
string s;
}

this attribute will remove namespace.
posted on Monday, July 21, 2008  by Anonymous @ 4:51 AM

Great Post.

Thanks
posted on Wednesday, July 30, 2008  by Anonymous @ 11:36 PM

worked for me as well.
Really saved lot of time, lucky I found this article

Thanks a lot.
posted on Saturday, September 20, 2008  by Monty @ 9:57 AM

anyone know why I get the characters '???' in front of my 'root' element now that I've taken off all the crap I dont want?
posted on Tuesday, September 30, 2008  by Anonymous @ 12:05 PM

??? is probably the 3 byte unicode encoding mark. You probably get that by default so XML readers know how to decode the specific unicode character strings. There are a number of ways to get rid of it if you need to, such as using the ASCII encoding, but you may want to keep them depending on what you are doing with the serialized datastream. If it's being saved to disk or sent across the wire and later will be deserialized, just leave them.
posted on Wednesday, November 05, 2008  by Anonymous123 @ 2:33 PM

This is one of the best methods and never imagined something like this existed also.....
BUT
I also have an issue like one other anonymous user. it causes "q1:" to go in front of every single element, including the root.

<q1:ExportData xmlns:q1="http://tempuri.org/XMLSchema.xsd">
<q1:Account AccountID="1010" Amount="13815026.0000000000">

I am not sure if i am doing anything incorrect or is it like this only...Please respond
posted on Wednesday, December 10, 2008  by Felipe @ 4:02 PM

For the last post:
I did this:

## Inside my Serialization Object ##

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("asp", "http://www.microsoft.com/");
ns.Add("rts", "http://www.realtimesites.com/");


## Inside my Objects

[XmlRoot("codegenerator",Namespace="http://www.realtimesites.com/", IsNullable=false)]
public class PageCodeGenerator
{
[XmlElement("region",Namespace="")]
public string Region
{
get;
set;
}
[XmlElement("code", Namespace = "")]
public string Code
{
get;
set;
}
}

### The result when I do the Serialization. Note also that the elements don't contain any namespace because I leave them in blank.

<xml version="1.0" encoding="utf-8"?>
<rts:codegenerator xmlns:asp="http://www.microsoft.com/" xmlns:rts="http://www.realtimesites.com/">
<code> something here... </code>
<region> something else right here </region>
</rts:codegenerator>

### the q1: Problem

That's because you are putting on the

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");

and empty value, and you are putting somthing on the Root element

[XmlRoot("codegenerator",Namespace="http://something", IsNullable=false)]
public class PageCodeGenerator
{
....
}

that will give you:

<q1:codegenerator .... />
<q1:code> ....
....


You must match at least one of your Qualified Name Spaces on the Root or just leave the Root and the XmlSerializerNamespaces empty.

That should do the work.
Hope this help
posted on Wednesday, December 17, 2008  by Emil @ 1:46 AM

Thanks for saving me time. I created a couple of extension methods for XmlSerializer so that you could easily serialize without namespaces:
Copy code to clipboard in IE or select code for Firefox
mySerializer.SerializeWithoutNameSpaces(myStream, myObj)


And here is the code for the extension class

Copy code to clipboard in IE or select code for Firefox
public static class XmlSerializerExtensions
    {
        public static void SerializeWithoutNamespaces(this XmlSerializer serializer, Stream stream, object o) {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            serializer.Serialize(stream, o, ns);
        }
        public static void SerializeWithoutNamespaces(this XmlSerializer serializer, XmlWriter xmlWriter, object o)
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            serializer.Serialize(xmlWriter, o, ns);
        }
        public static void SerializeWithoutNamespaces(this XmlSerializer serializer, TextWriter textWriter, object o)
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            serializer.Serialize(textWriter, o, ns);
        }
    }
posted on Monday, December 22, 2008  by John Saunders (mvp) @ 7:21 AM

Sorry to learn so many have been having troubles with the XmlSerializer - and that I didn't know about it! I'm answering this kind of question all the time over at http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/threads. Come on over and share your pain and your victories.
posted on Friday, February 20, 2009  by Anonymous @ 6:31 AM

Great post, just what I was looking for.
posted on Sunday, March 08, 2009  by Peter Lykkegaard @ 9:03 AM

Hmm you are all aware that prober formed XML must have namespaces etc?
posted on Monday, April 06, 2009  by Anonymous @ 3:19 AM

Thank you so much ! I was close to get nuts ;-)
posted on Wednesday, May 06, 2009  by ddBoarm @ 9:34 AM

I am trying to serialize my XSD. Maybe I'm just a little dense but I cannot figure out what OBJECT I am suppose to insert in the following:

XmlSerializer serializer = new XmlSerializer(typeof(OBJECT);

Maybe just a hint or something. I have the following code snippet:

//declarations
static XmlSchema XGIL_SKEMA;
XmlTextWriter xgi_writer = null;

XmlSerializer serializer = new XmlSerializer(typeof(XmlSchema));
xgi_writer = new XmlTextWriter(myFile, null);
serializer.Serialize(xgi_writer, XGIL_SKEMA);

//end

The result is a file that exactly mirrors my XSD. This does me no good. I want the snippet to generate a sample XML file. In the instantiation of the new XmlSerializer, I am using the XmlSchema object (class) from System.Xml.XmlSchema. What else am I doing wrong?

Please help
posted on Wednesday, June 10, 2009  by Chathuranga Wijeratna @ 12:00 PM

I was having issues around Xml serializations with WCF REST Starter kit. Digging into the issue showed me like it's something to do with namespaces. But where I ended up was not really with the namespaces.
When I created the XML types through Paste as XML type plug in, it properly generated the type with private fields and public properties. But with resharper guidence, I made normal properties to auto properties, which made the issue. So it seems that private fields are a must with XMl serialization.(I need to find why ...hope I'll find some time for it).
posted on Wednesday, July 15, 2009  by Kevin @ 4:16 AM

I solved the annoying xsi and xsd and q1 issues all at once, by simply using

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "http://whatevernamespaceyouwantinyourrootelement");

the xmlns:xsi and xmlns:xsd are gone, and no magic q1 crap anymore!
posted on Tuesday, August 04, 2009  by Kitty @ 9:18 AM

Thanks for help with q1 problem. I have to combine several information from your posts. Ill write it here.

[XmlRoot(Namespace = "http://namespace")]
public class clsToSerialize
{ ... }

//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "http://namespace");

using (XmlWriter w = XmlWriter.Create(FileName, writerSettings))
{
s.Serialize(w, input, ns);
}

so thank you one more time...
posted on Friday, August 21, 2009  by Anonymous @ 4:39 AM

Wicked! Thanks ;)
posted on Friday, August 28, 2009  by Anonymous @ 6:52 AM

This post helps me a lot....
Thanks for such a helpful post..
posted on Friday, September 04, 2009  by Anonymous @ 7:14 AM

Thanks a lot. I had a lot of trouble with this. First, I got an error on deserialization because of the xmlns - which I *did* cater for in my object. Searching the internet to find out why this particular attribute should give me more problems than any other left me empty handed. Then when I serialized, I noticed the serializer conveniently added those attributes back for me in the xml file.

WTF! Sometimes Microsoft can be really stupid!
posted on Tuesday, September 08, 2009  by Anonymous @ 7:31 AM

Awesome. Thanks!

Microsoft-generated classes were outputting the namespaces by default, and the provider I'm integrating with does not support them. This gave me a 5-minute solution (to integrate into my XML-serialization wrapper class).
posted on Wednesday, November 04, 2009  by Anonymous @ 6:33 PM

Thanks, this likely saves me hours and a headache!
posted on Monday, November 09, 2009  by evilripper @ 2:14 AM

thanks a lot!! very good article, i had the same problem!! bye
posted on Tuesday, December 22, 2009  by Ariel @ 1:52 PM

Thanks, exactly what I was looking for!
posted on Saturday, January 16, 2010  by Anonymouse @ 1:05 PM

Just what I was looking for, also. Thanks!
posted on Tuesday, February 23, 2010  by Anonymous @ 3:57 PM

Like so many others, this was VERY helpful to me. Thanks, and thanks for the comments that finished out the article.


New Post Notification

Search Posts

Recent Posts


About Meeself
People call me Bobby DeRosa
I live somewhere in San Diego, CA
MCSD, MCAD, MCP

This theme was adapted from fUnique by fahlstad        Icons by FamFamFam        XHTML 1.0 Strict; tuned for Mozilla-powered browsers

Admin Login Administrator Login
Invalid login attempts are logged.
  Username:
  Password: