Remove Namespaces During XML Serialization

后端 未结 2 955
难免孤独
难免孤独 2020-12-19 16:20

Given this generic serialization code:

public virtual string Serialize(System.Text.Encoding encoding)
{
 System.IO.StreamReader streamReader = null;
 System.         


        
2条回答
  •  伪装坚强ぢ
    2020-12-19 17:13

    You can remove the namespaces like this:

    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add(string.Empty, string.Empty);
    ns.Add(string.Empty, "Com.Foo.Request");
    Serializer.Serialize(xmlWriter, this, ns);
    

    As for adding the doctype, I know it's possible to make a custom XmlWriter and just override WriteStartDocument with a method that makes a call to WriteDocType, but I kind of hope someone else knows an easier way than that.

    EDIT: Incidentally, I strongly recommend using using:

    using(System.Xml.XmlWriter xmlWriter = XmlWriter.Create(etc.))
    {
      // use it here.
    }
    

    It automatically handles tidying up of the streams by calling the Dispose method when the block ends.

提交回复
热议问题