views:

2218

answers:

2

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=”…”?

+21  A: 
//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);

stole it form this guy

Jeremy
Exactly. Works like a charm.
Dave Van den Eynde
+1  A: 

There is an alternative - you can provide a member of type XmlSerializerNamespaces in the type to be serialized. Decorate it with the XmlNamespaceDeclarations attribute. Add the namespace prefixes and URIs to that member. Then, any serialization that does not explicitly provide an XmlSerializerNamespaces will use the namespace prefix+URI pairs you have put into your type.

Example code, suppose this is your type:

[XmlRoot(Namespace = "urn:mycompany.2009")]
public class Person {
  [XmlAttribute] 
  public bool Known;
  [XmlElement]
  public string Name;
  [XmlNamespaceDeclarations]
  public XmlSerializerNamespaces xmlns;
}

You can do this:

var p = new Person
  { 
      Name = "Charley",
      Known = false, 
      xmlns = new XmlSerializerNamespaces()
  }
p.xmlns.Add("",""); // default namespace is emoty
p.xmlns.Add("c", "urn:mycompany.2009");

And that will mean that any serialization of that instance that does not specify its own set of prefix+URI pairs will use the "p" prefix for the "urn:mycompany.2009" namespace. It will also omit the xsi and xsd namespaces.

The difference here is that you are adding the XmlSerializerNamespaces to the type itself, rather than employing it explicitly on a call to XmlSerializer.Serialize(). This means that if an instance of your type is serialized by code you do not own (for example in a webservices stack), and that code does not explicitly provide a XmlSerializerNamespaces, that serializer will use the namespaces provided in the instance.

Cheeso
1. I don't see the difference. You're still adding the default namespace to an instance of XmlSerializerNamespaces.
Dave Van den Eynde
2. This pollutes the classes more. My objective is not to use certain namespace, my objective is not to use namespaces at all.
Dave Van den Eynde
I added a note about the difference between this approach and that of specifying the XmlSerializerNamespaces during serialization only.
Cheeso