C#实现对象的Xml格式序列化及反序列化
要序列化的对象的类:
[Serializable]
public class Person
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name=value;
}
}
public string Sex;
public int Age=31;
public Course[] Courses;
public Person()
{
}
public Person(string Name)
{
name=Name;
Sex="男";
}
}
[Serializable]
public class Course
{
public string Name;
[XmlIgnore]public string Description;
public Course()
{
}
public Course(string name,string description)
{
Name=name;
Description=description;
}
}
public class Person
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name=value;
}
}
public string Sex;
public int Age=31;
public Course[] Courses;
public Person()
{
}
public Person(string Name)
{
name=Name;
Sex="男";
}
}
[Serializable]
public class Course
{
public string Name;
[XmlIgnore]public string Description;
public Course()
{
}
public Course(string name,string description)
{
Name=name;
Description=description;
}
}
进行序列化及反序列化的测试类:
class Test
{
//序列化
public void Serialiaze()
{
Person c=new Person("cyj")
c.Courses=new Course[2];
c.Courses[0]=new Course("英语","交流工具")
c.Courses[1]=new Course("数学","自然科学")
XmlSerializer xs=new XmlSerializer(typeof(Person));
Stream stream = new FileStream("c:\\cyj.xml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
xs.Serialize(stream, c);
stream.Close();
}
//反序列化
public void Deserialize()
{
XmlSerializer xs=new XmlSerializer(typeof(Person));
Stream stream = new FileStream("c:\\cyj.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Person p=(Person)xs.Deserialize(stream);
Console.WriteLine(p.Name);
Console.WriteLine(p.Age.ToString());
Console.WriteLine(p.Courses.Length.ToString());
Console.Read();
}
}
{
//序列化
public void Serialiaze()
{
Person c=new Person("cyj")
c.Courses=new Course[2];
c.Courses[0]=new Course("英语","交流工具")
c.Courses[1]=new Course("数学","自然科学")
XmlSerializer xs=new XmlSerializer(typeof(Person));
Stream stream = new FileStream("c:\\cyj.xml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
xs.Serialize(stream, c);
stream.Close();
}
//反序列化
public void Deserialize()
{
XmlSerializer xs=new XmlSerializer(typeof(Person));
Stream stream = new FileStream("c:\\cyj.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Person p=(Person)xs.Deserialize(stream);
Console.WriteLine(p.Name);
Console.WriteLine(p.Age.ToString());
Console.WriteLine(p.Courses.Length.ToString());
Console.Read();
}
}
格式化后Xml的文档内容为:
<?xml version="1.0"?>
<Person xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Sex>男</Sex>
<Age>31</Age>
<Courses>
<Course>
<Name>英语</Name>
</Course>
<Course>
<Name>数学</Name>
</Course>
</Courses>
<Name>cyj</Name>
</Person>
<Person xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Sex>男</Sex>
<Age>31</Age>
<Courses>
<Course>
<Name>英语</Name>
</Course>
<Course>
<Name>数学</Name>
</Course>
</Courses>
<Name>cyj</Name>
</Person>