Search code examples
c#.netxml-serializationxml-declaration

How do I get rid of the xmlns declarations inserted by the XmlSerializer?


I have this type:

[Serializable, DataContract]
public class A
{
  [DataMember(Order = 1)]
  public int P1 { get; set; }
  [DataMember(Order = 2)]
  public XmlSerializableDictionary<string, string> P2 { get; set; }
}

Where XmlSerializableDictionary is borrowed from .NET XML serialization gotchas?.

The XmlSerializer produces the following XML:

<?xml version="1.0"?>
<A xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <P1>17</P1>
  <P2>
    <item>
      <key>
        <string>Hello World!</string>
      </key>
      <value>
        <string>xo-xo</string>
      </value>
    </item>
    <item>
      <key>
        <string>Good Bye!</string>
      </key>
      <value>
        <string>xi-xi</string>
      </value>
    </item>
  </P2>
</A>

The only things that I wish to get rid of are the xmlns declarations on the root element. How do I do it? Thanks.


Solution

  • Via XmlSerializerNamespaces:

        var ns = new XmlSerializerNamespaces();
        ns.Add("", ""); // this line is important... honest!
        var ser = new XmlSerializer(type);
        ser.Serialize(destination, obj, ns);