1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
using System;
using System.IO;
using System.Collections;
using System.Xml.Serialization;
public class Test
{
public static void Main()
{
Test t=new Test();
t.Create("icollection.xml");
t.Read("icollection.xml");
}
private void Create(string filename)
{
Employees emps=new Employees();
/* Note that only the collection is serialized, not
* the CollectionName or any other public property of
* the class.
*/
emps.CollectionName="Employees";
Employee john100=new Employee("John", "100xxx");
emps.Add(john100);
XmlSerializer ser=new XmlSerializer(typeof(Employees));
TextWriter writer=new StreamWriter(filename);
ser.Serialize(writer, emps);
writer.Close();
}
private void Read(string filename)
{
XmlSerializer ser=new XmlSerializer(typeof(Employees));
FileStream fs=new FileStream(filename, FileMode.Open);
Employees emps;
emps=(Employees)ser.Deserialize(fs);
fs.Close();
/* Not serialized! */
Console.WriteLine("Collection name: "+emps.CollectionName);
foreach(Employee emp in emps)
{
Console.WriteLine("Employee name: "+emp.EmpName);
Console.WriteLine("Employee ID: "+emp.EmpID);
}
}
}
public class Employees:ICollection
{
public string CollectionName;
private ArrayList empArray=new ArrayList();
public Employee this[int index]
{
get {
return((Employee)empArray[index]);
}
}
public void CopyTo(Array a, int index)
{
empArray.CopyTo(a, index);
}
public int Count
{
get {
return(empArray.Count);
}
}
public object SyncRoot
{
get {
return(this);
}
}
public bool IsSynchronized
{
get {
return(false);
}
}
public IEnumerator GetEnumerator()
{
return(empArray.GetEnumerator());
}
public void Add(Employee newEmployee)
{
empArray.Add(newEmployee);
}
}
public class Employee
{
public string EmpName;
public string EmpID;
public Employee()
{}
public Employee(string empName, string empID)
{
EmpName=empName;
EmpID=empID;
}
}
|