如此处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
是一个属性。
答案 0 :(得分:1)
默认情况下,.NET XmlSerializer
会在序列化ArrayOfItem
时生成List<T>
元素。
您可以通过创建一个派生自List<T>
:
[Serializable]
public class Persons : List<Person>
{
}
或者,当它是属性时,使用名称标记XmlElement
:
[XmlElement("Persons")]
public List<Person> Persons
{
get;
set;
}