Collection mainly refers to like array, ArrayList, List, Dictionary, hashtable these data types, we usually use a lot. If you have a member of a collection type in a class, what should you do with the XML serialization of that class? It should be said that in. NET this is relatively simple, as long as the creation of a XmlSerializer class can help you automatically, but sometimes you may need to exert more control over the automatic serialization process, such as the structure of XML is fixed, you have to follow the requirements to generate XML structure.
The use of different properties can be flexible control of the generated XML, here I will not introduce more, mainly about how to serialize the more complex collection structure. The following method is valid for all collection that implement the IEnumerable interface.
I use the examples in MSDN, but instead of using arrays or ArrayList, I use the more advanced data type List<t>, and I want to provide a point of reference for students who use list<t> while explaining how to serialize XML.
Serialization of a list<t>
The following code demonstrates how to serialize a list<t>, and in fact, like serializing other classes, throw the class to the Serialize () function.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
Namespace Serializecollection
{
Class program
{
static void Main (string[] args)
{
Progra M test = new program ();
Test. Serializedocument ("E:\\books.xml");
}
public void serializedocument (string filename)
{
//creates a new XmlSerializer.
XmlSerializer s =
New XmlSerializer (typeof (Myrootclass));
//Writing the file requires a StreamWriter.
TextWriter mywriter = new StreamWriter (filename);
//Creates an instance of the class to serialize.
Myrootclass Myrootclass = new Myrootclass ();
//create Items
Item item1 = new Item ()
//Sets the Objects ' properties.
Item1. ItemName = "Widget1";
Item1. ItemCode = "W1";
Item1. Itemprice = 231;
Item1. itemquantity = 3;
Item item2 = new Item ();
//Sets the Objects ' properties.
Item2. ItemName = "Widget2";
Item2. ItemCode = "W2";
Item2. Itemprice = 800;
Item2. Itemquantity = 2;
//Sets The class ' s Items to the list.
MyRootClass.Items.Add (item1);
MyRootClass.Items.Add (ite m2);
/* Serializes the class, writes it to disk, and closes
the TextWriter. */
S.serialize (Mywriter, MYROOTC LASS);
Mywriter.close ();
}
}
//This are the class that would be serialized.
[Serializable]
public class Myrootclass
{
Public myrootclass ()
{
items = new list<item> ();
}
Private list<item> items;
Public list<item> Items
{
Get {return items;}
Set {items = value;}
}
}
public class Item
{
[XmlElement (elementname = ' OrderItem ')]
public string itemname;
public string ItemCode;
Public decimal Itemprice;
public int itemquantity;
}
}