如何序列化对象数组

时间:2014-12-08 12:26:42

标签: c# .net winforms xmlserializer

如此处http://msdn.microsoft.com/en-us/library/szzyf24s%28v=vs.110%29.aspx所示,我们可以生成xml of object:

MySerializableClass myObject = new MySerializableClass();
// Insert code to set properties and fields of the object.
XmlSerializer mySerializer = new 
XmlSerializer(typeof(MySerializableClass));
// To write to a file, create a StreamWriter object.
StreamWriter myWriter = new StreamWriter("myFileName.xml");
mySerializer.Serialize(myWriter, myObject);
myWriter.Close();

这很好用,但现在我有了Listof MySerializableClass

List<Object> lObj = new List<Object>();
Person obj1 = new Person ();
Person obj2 = new Person ();

lobj.add(obj1);
lobj.add(obj2);

CreateXMLOFList(lobj);

您能否建议我编写一个可以生成List of collection的单个XML的函数:

示例:

<Person>
<Name>
Joy
</Name>
</Person>

<Person>
<Name>
 Steive
</Name>
</Person>

此处Person是一个类,Name是一个属性。

1 个答案:

答案 0 :(得分:1)

默认情况下,.NET XmlSerializer会在序列化ArrayOfItem时生成List<T>元素。

您可以通过创建一个派生自List<T>

的自己的类来规避这一点
[Serializable]
public class Persons : List<Person>
{
}

或者,当它是属性时,使用名称标记XmlElement

[XmlElement("Persons")]
public List<Person> Persons
{
    get;
    set;
}