如何摆脱XmlSerializer插入的xmlns声明?

时间:2011-09-24 09:39:23

标签: c# .net xml-serialization xml-declaration

我有这种类型:

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

.NET XML serialization gotchas?借用XmlSerializableDictionary

XmlSerializer生成以下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>

我希望摆脱的唯一内容是根元素上的xmlns声明。我该怎么做?感谢。

1 个答案:

答案 0 :(得分:1)

通过XmlSerializerNamespaces

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