C#对象的 Xml序列化与反序列化
using System.Collections.Generic;
public class Person
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Sex;
public int Age = 31;
public List<Course> Courses=new List<Course>();
public Person()
{
}
public Person(string Name)
{
name = Name;
Sex = "男";
}
}
public class Course
{
public string Name;
public string Description;
public Course()
{
}
public Course(string name, string description)
{
Name = name;
Description = description;
}
}
/// <summary>
/// 序列化
/// </summary>
/// <param name="filePath"></param>
public void Serialiaze(String filePath)
{
Person c = new Person("James Chen");
c.Courses.Add(new Course("高等数学","思维工具"));
c.Courses.Add(new Course("大学英语", "交流工具"));
c.Courses.Add(new Course("离散数学", "计算机理论"));
XmlSerializer xs = new XmlSerializer(typeof(Person));
Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
xs.Serialize(stream, c);
stream.Close();
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="filePath"></param>
public void Deserialize(String filePath)
{
XmlSerializer xs = new XmlSerializer(typeof(Person));
Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Person p = (Person)xs.Deserialize(stream);
Response.Write(p.Name+"<br>");
Response.Write(p.Age.ToString() + "<br>");
Response.Write(p.Courses.Count.ToString());
stream.Close();
}<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Sex>男</Sex>
<Age>31</Age>
<Courses>
<Course>
<Name>高等数学</Name>
<Description>思维工具</Description>
</Course>
<Course>
<Name>大学英语</Name>
<Description>交流工具</Description>
</Course>
<Course>
<Name>离散数学</Name>
<Description>计算机理论</Description>
</Course>
</Courses>
<Name>James Chen</Name>
</Person>
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hb_cattle/archive/2008/01/05/2026373.aspx