如何覆盖 c# 中 List() 中每个列表项的序列化名称?
我有一个或多或少像这样的结构:
[Serializable]
[XmlRoot("Customer")]
public struct TCustomer
{
string CustomerNo;
string Name;
}
我有时将此结构序列化为 XML 作为单个对象,这工作得很好,但有时我也需要序列化一个 List<>这个结构体的。
我使用它来设置顶级元素名称:
[Serializable]
[XmlRoot("Customers")]
public class CustomerList : List<TCustomer> { }
XmlSerializer,但是,坚持调用每个列表项 TCustomer。如何告诉 XmlSerializer 使用名称 Customer 而不是 TCustomer?
I have a struct more or less like this:
[Serializable]
[XmlRoot("Customer")]
public struct TCustomer
{
string CustomerNo;
string Name;
}
I sometimes serialize this this struct to XML as a single object, which works fine, but I also sometimes need to serialize a List<> of this struct.
I've used this to set the top level element name:
[Serializable]
[XmlRoot("Customers")]
public class CustomerList : List<TCustomer> { }
XmlSerializer however, insists on calling each list item TCustomer. How can I tell XmlSerializer to use the name Customer instead of TCustomer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
希望有帮助
Hope it helps
XmlRoot
属性仅适用于根元素,因此当您序列化CustomerList
时,它不适用于TCustomer
。如果不实现您自己的序列化,我认为您无法将
TCustomer
更改为在CustomerList
类中序列化为Customer
。但是你可以做这样的事情...这应该给你类似于以下的 xml:
这从通用列表中更改了你的 CustomerList,但它允许你控制你的命名。
The
XmlRoot
attribute only applies for the root element, so it doesn't apply forTCustomer
when you are serializingCustomerList
.Without implementing your own serialization, I don't think you can change
TCustomer
to serialize asCustomer
within theCustomerList
class. But you can do something like this...That should give you xml similar to:
This changes your CustomerList from a generic list, but it allows you to control your naming.
感谢所有的答案。然而,我的具体问题的解决方案却很简单:
Thank's for all the answers. The sollution to my specific problem however, turned out to be as simple as:
我从未在类/结构级别尝试过此操作,但当我需要序列化类内的列表时,这就是我的做法。
I've never tried this at the class /struct level, but this is how I do it when I need to serialize a list inside a class.
您可以实现 IXmlSerialized 来自定义某些对象的序列化方式:
IXmlSerialized Interface
不管怎样,序列化程序似乎调用了
TCustomer
项目的类型,因为这是List
(TCustomer
是 ???,其中 ??? 是泛型参数类型TCustomer
的实际类型)。我不会在不实现 IXmlSerialized 的情况下改变 XmlSerializer 序列化对象的方式(我的意思是,避免序列化后文本替换或其他任何操作!)。
You can implement
IXmlSerializable
in order to customize the way some object is serialized:IXmlSerializable Interface
Anyway, it seems that serializer calls
TCustomer
the type of items because this is the actual type of theList
(TCustomer
is ???, where ??? will be the actual type of the generic parameter typeTCustomer
).I wouldn't change the way
XmlSerializer
serializes objects without implementingIXmlSerializable
(I mean, avoid a post-serializing text replacement or whatever!).