简体   繁体   中英

How to serialize Array of object

As shown here http://msdn.microsoft.com/en-us/library/szzyf24s%28v=vs.110%29.aspx , we can generate 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();

This is working fine, but now I am having Listof MySerializableClass

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

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

CreateXMLOFList(lobj);

Can you suggest me to write a function which can generate single XML of List of collection:

example:

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

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

here Person is a class and Name is a property.

By default, the .NET XmlSerializer will generate an ArrayOfItem element when serializing a List<T> .

You can circumvent this by creating an own class that derives from List<T> :

[Serializable]
public class Persons : List<Person>
{
}

Or, when it is a property, mark the XmlElement with a name:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM