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(); }}
Remember Me
a@href@title, b, i, strike
Powered by: newtelligence dasBlog 2.0.7226.0
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2008R. Aaron Zupancic
E-mail