Tuesday, May 30, 2006

Removing default namespaces while serializing

When we serialize an object into a MemoryStream using an XmlSerializer
and load it to an XmlDocument; following two namespaces will be added by default..

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

Following code will help to remove them.

System.IO.MemoryStream ms = new System.IO.MemoryStream();
XmlDocument doc = new XmlDocument();

// Removes defaultnamespace being printed at child elements unnecessarily.
XmlSerializerNamespaces blankNamspace = new XmlSerializerNamespaces();

// Adds a prefix-namespace[blank] pair to
// an System.Xml.Serialization.XmlSerializerNamespaces object.
// (The prefix associated with an XML namespace,An XML namespace)
blankNamspace.Add(String.Empty, String.Empty);

XmlSerializer serializer = new XmlSerializer(typeof(ClassName));
serializer.Serialize(ms, this,blankNamspace);

ms.Position = 0;
doc.Load(ms);

No comments:

Post a Comment