.NET Framework提供了多种序列化对象的方法,二进制,XML, SOAP,而在系统中应用往往使用对象序列化来暂存或缓存对象状态。
第一步,序列化对象到字串
public static string GetObjectXML(object e)
{
XmlSerializer serilizer = new XmlSerializer(typeof(Employee));

System.Text.StringBuilder sbXML = new StringBuilder();

System.IO.StringWriter writer = new System.IO.StringWriter(sbXML);

serilizer.Serialize(writer, e);

writer.Close();

return sbXML.ToString();
}
第二步,将字串反序列化为对象
public static Employee GetObjectFromXML(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(Employee));

System.IO.StringReader reader = new System.IO.StringReader(xml);

Employee emp = (Employee)serializer.Deserialize(reader);

return emp;
}
Employee是自定义对象,XML 序列化只能序列化public属性,无值的属性不生成XML Tag.
调用示例:
static void Main(string[] args)
{
Employee emp = new Employee();
emp.FirstName = "Johnson";
emp.LastName = "Yang";
emp.Id = 1;

Console.WriteLine("{0}", GetObjectXML(emp));

Console.WriteLine("First Name = {0}", GetObjectFromXML(GetObjectXML(emp)).FirstName);
}


//Employee

public class Employee
{
member variables

public properties
}
//输出结果
<?xml version="1.0" encoding="utf-16"?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http:
//www.w3.org/2001/XMLSchema">
<Id>1</Id>
<FirstName>Johnson</FirstName>
<LastName>Yang</LastName>
<BirthDay>2007-03-13T21:51:33.078125+08:00</BirthDay>
</Employee>
First Name = Johnson
第一步,序列化对象到字串















第二步,将字串反序列化为对象











Employee是自定义对象,XML 序列化只能序列化public属性,无值的属性不生成XML Tag.
调用示例:





















//输出结果
<?xml version="1.0" encoding="utf-16"?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http:
//www.w3.org/2001/XMLSchema">
<Id>1</Id>
<FirstName>Johnson</FirstName>
<LastName>Yang</LastName>
<BirthDay>2007-03-13T21:51:33.078125+08:00</BirthDay>
</Employee>
First Name = Johnson