Tuesday, December 13, 2005
« DevUtah - 2nd Geek Dinner - Dec 20th | Main | Somehow This Just Makes Sense - Spidey S... »

Recently I've had the need to serialize an object using the XmlSerializer.  By default, when you serialize an object it will automatically add the default xmlns:xsd="..." and xmlns:xsi="..." namespaces to the root element of the xml document.  In my particular case this was not desirable, but there wasn't any obvious way to remove them.  As it turns out, there really is, but it's semi-obscure.

As it turns out, I did this a few years ago back in my .NET 1.0 days, but it had since evaporated from my memory, but I found a nice little blog post that jogged my memory.  All you have to do is use an XmlSerializerNamespaces object with an empty namespace.  The .NET framework will inspect this object for any namespaces.  A null reference or zero entries will cause the serializer to include the defaults.  Any namespaces (even empty ones) override the default behavior, thereby not including the default.  A simple example might resemble the following:

internal string SerializeCustomer(Customer cust) {
   using ( StringWriter writer = new StringWriter(CultureInfo.InvariantCulture) ) {
      XmlSerializer ser = new XmlSerializer(typeof(Customer));
      // remove the xsd and xsi namespaces from the serialization output by
      // appending a blank namespace

      XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
      xsn.Add(string.Empty, string.Empty);
      // serialize the object and extract the result from the writer
      ser.Serialize(writer, cust, xsn);
      return writer.ToString();
   }
}

Tuesday, December 13, 2005 4:33:00 AM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [5]  |  Trackback
Tuesday, June 06, 2006 4:45:00 AM (Mountain Standard Time, UTC-07:00)
- rated a 5.
just what i need!!
anonymous rating
Thursday, May 10, 2007 8:18:00 AM (Mountain Standard Time, UTC-07:00)
Perfect first time. Thank you. :)
Wednesday, July 04, 2007 11:49:00 AM (Mountain Standard Time, UTC-07:00)
- rated a 5.
Exactly what I need =)



Thanks
anonymous rating
Friday, January 04, 2008 11:21:00 PM (Mountain Standard Time, UTC-07:00)
- rated a 5.
Perfect!
Mikhail Kozhevnikov
Friday, April 11, 2008 2:26:00 AM (Mountain Standard Time, UTC-07:00)
Thanks!
Ed
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, i, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview