complete code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Test_XmlSerialize
{
[Serializable]
public class Employee
{
public string Name { get; set; }
}
[Serializable]
public class Company
{
public string CompName { get; set; }
public List<Employee> Employees { get; set; }
public override string ToString()
{
string s = string.Empty;
s += this.CompName + Environment.NewLine;
s += "Employees:" + Environment.NewLine;
foreach (var e in this.Employees)
{
s += e.Name + Environment.NewLine;
}
return s;
}
}
class Program
{
static void Main(string[] args)
{
try
{
Company comp = new Company()
{
CompName = "comp1",
Employees = new List<Employee>()
};
comp.Employees.Add(new Employee() { Name = "emp1" });
comp.Employees.Add(new Employee() { Name = "emp2" });
using (StreamWriter sw = new StreamWriter(@"d:\tmp\1.txt"))
{
XmlSerializer ser = new XmlSerializer(typeof(Company),
new Type[] { typeof(Employee) });
ser.Serialize(sw, comp);
}
using (StreamReader sr = new StreamReader(@"d:\tmp\1.txt"))
{
XmlSerializer ser = new XmlSerializer(typeof(Company),
new Type[] { typeof(Employee) });
Company c2 = ser.Deserialize(sr) as Company;
if (c2 != null)
Console.WriteLine(c2);
};
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}