Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

c# - How to Serialize List<T>?

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
}

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...

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use the 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();

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; } 
}

Edit:

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>

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...