Remove Namespaces During XML Serialization

后端 未结 2 954
难免孤独
难免孤独 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.

    0 讨论(0)
  • 2020-12-19 17:18

    If you just want to remove the namespace aliases, then as already shown you can use XmlSerializerNamespaces to force XmlSerializer to use the namespace explicitly (i.e. xmlns="blah") on each element, rather than declaring an alias and using the alias instead.

    However, regardless of what you do with the aliases, the fundamental name of that element is REQUEST_GROUP in the Com.Foo.Request namespace. You can't remove the namespace completely without that representing a breaking change to the underlying data - i.e. somebody somewhere is going to get an exception (due to getting data it didn't expect - specifically REQUEST_GROUP in the root namespace). In C# terms, it is the difference between System.String and My.Custom.String - sure, they are both called String, but that is just their local name.

    If you want to remove all traces of the namespace, then a pragmatic option would be to edit away the Namespace=... entries from [XmlRoot(...)] and [XmlType(...)] (plus anywhere else that isn't shown in the example).

    If the types are outside of your control, you can also do this at runtime using XmlAttributeOverrides - but a caveat: if you create an XmlSerializer using XmlAttributeOverrides you must cache and re-use it - otherwise your AppDomain will leak (it creates assemblies on the fly per serializer in this mode, and assemblies cannot be unloaded).

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