更新时间:2023-12-03 18:54:46
如果您只想删除名称空间 aliases ,那么如已显示的那样,您可以使用 XmlSerializerNamespaces
强制 XmlSerializer
在每个元素上显式使用名称空间 (即 xmlns ="blah"
),而不是声明别名并改用别名
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.
但是,无论您使用别名做什么,该元素的基本名称都是 Com.Foo.Request
名称空间中的 REQUEST_GROUP
.您不能完全删除名称空间 ,除非该名称空间表示对基础数据的重大更改-即某个地方的某人将要获取异常(由于获取了意外的数据-特别是根名称空间中的REQUEST_GROUP
).用C#术语来说,这是 System.String
和 My.Custom.String
之间的区别-当然,它们都被称为 String
,但是只是他们的 local 名称.
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.
如果您想要要删除名称空间的所有痕迹,那么务实的选择是从 [XmlRoot]中删除
和 Namespace = ...
条目(...)] [XmlType(...)]
(以及示例中未显示的其他任何地方).
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).
如果类型不在您的控制范围内,则还可以在运行时使用 XmlAttributeOverrides
进行操作-但要注意:如果使用 XmlAttributeOverrides创建
XmlSerializer
您 必须 缓存并重新使用它-否则您的 AppDomain
会泄漏(它会动态地 per序列化器(在这种模式下,程序集不能卸载).
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).