如何序列化 List<T>? [英] How to Serialize List&lt;T&gt;?

查看:19
本文介绍了如何序列化 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
}

我想序列化 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

推荐答案

您可以使用 XMLSerializer:

var aSerializer = new XmlSerializer(typeof(A));
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
aSerializer.Serialize(sw, new A()); // pass an instance of A
string xmlResult = sw.GetStringBuilder().ToString();

为了使其正常工作,您还需要对您的类型进行 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.

这篇关于如何序列化 List<T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆