XmlSerializer: remove unnecessary xsi and xsd namespaces

Dave Van den Eynde picture Dave Van den Eynde · Apr 17, 2009 · Viewed 108k times · Source

Is there a way to configure the XmlSerializer so that it doesn't write default namespaces in the root element?

What I get is this:

<?xml ...>
<rootelement xmlns:xsi="..." xmlns:xsd="...">
</rootelement>

and I want to remove both xmlns declarations.

Duplicate of: How to serialize an object to XML without getting xmlns=”…”?

Answer

Jeremy picture Jeremy · Apr 17, 2009
//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)