如何序列化列表< T> ;? [英] How to Serialize List<T>?
问题描述
我有A级.B级和C级是A级的一部分.
I have Class A. Class B and Class C are part of Class A.
Class A
{
//Few Properties of Class A
List<typeof(B)> list1 = new List<typeof(B)>()
List<typeof(C)> list2 = new List<typeof(C)>()
Nsystem NotSystem { get; set; } // Enum Property Type
}
public enum Nsystem {
A = 0,
B = 1,
C = 2
}
我想序列化Class A,并希望使用它生成XML;我也想序列化list1和list2以及Enum ...
I want to Serialize Class A and want to produce XML with it; I also want to serialize list1 and list2 and also the Enum...
什么是序列化此XML的好方法,因为我需要将对象转换为XML并将XML转换为对象的功能...
What is a good approach to Serialize this XML because I need the functionality of converting an Object into XML and XML into an Object ...
执行此操作有哪些好的选择? 谢谢
What are some good options to do this? Thanks
推荐答案
您可以使用要使其正常工作,您还需要在类型上添加xml批注,以确保其使用正确的命名序列化,即:
For this to work properly you will also want xml annotations on your types to make sure it is serialized with the right naming, i.e.:
public enum NSystem { A = 0, B = 1, C = 2 }
[Serializable]
[XmlRoot(ElementName = "A")]
Class A
{
//Few Properties of Class A
[XmlArrayItem("ListOfB")]
List<B> list1;
[XmlArrayItem("ListOfC")]
List<C> list2;
NSystem NotSystem { get; set; }
}
Enum
属性被序列化,该属性的名称包含XML元素,其枚举值作为XML值,即,如果示例中的属性NotSystem
具有值C
,它将被序列化为
Enum
properties are serialized by default with the name of the property as containing XML element and its enum value as XML value, i.e. if the property NotSystem
in your example has the value C
it would be serialized as
<NotSystem>C</NotSystem>
当然,您始终可以通过执行适当的注释来更改属性序列化的方式,即使用[XmlAttribute]
使其序列化为属性,或者使用[XmlElement("Foobar")]
使其序列化使用Foobar
作为元素名称.有关MSDN的更多详细文档,请查看上面的链接.
Of course you can always change the way the property is serialized by doing a proper annotation, i.e using [XmlAttribute]
so it's serialized as an attribute, or [XmlElement("Foobar")]
so it's serialized using Foobar
as element name. More extensive documentation is available on MSDN, check the link above.
这篇关于如何序列化列表< T> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!