要序列化的对象的类:
[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;
}
}
进行序列化及反序列化的测试类:
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();
}
}
格式化后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>
新闻热点
疑难解答