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
>