Serializing object with no namespaces using DataContractSerializer

前端 未结 2 1488
南笙
南笙 2020-12-08 10:11

How do I remove XML namespaces from an object\'s XML representation serialized using DataContractSerializer?

That object needs to be serialized to a very simple outp

相关标签:
2条回答
  • 2020-12-08 10:20

    If you have your heart set on bypassing the default behavior (as I currently do), you create a custom XmlWriter that bypasses writing the namespace.

    using System.IO;
    using System.Xml;
    
    public class MyXmlTextWriter : XmlTextWriter
    {
      public MyXmlTextWriter(Stream stream)
        : base(stream, null)
      {
      }
    
      public override void WriteStartElement(string prefix, string localName, string ns)
      {
        base.WriteStartElement(null, localName, "");
      }
    }
    

    Then in your writer consumer, something like the following:

    var xmlDoc = new XmlDocument();
    DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
    using (var ms = new MemoryStream())
    {
      using (var writer = new MyXmlTextWriter(ms))
      {
        serializer.WriteObject(writer, obj);
        writer.Flush();
        ms.Seek(0L, SeekOrigin.Begin);
        xmlDoc.Load(ms);
      }
    }
    

    And the output will have namespace declarations in it, but there will be no usages as such:

    <TestObject xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <Items xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <string>Item1</string>
        <string>Item2</string>
      </Items>
    </TestObject>
    
    0 讨论(0)
  • 2020-12-08 10:27

    You need to mark the classes you want to serialize with:

    [DataContract(Namespace="")]
    

    In that case, the data contract serializer will not use any namespace for your serialized objects.

    Marc

    0 讨论(0)
提交回复
热议问题