The class of the object to serialize:
[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= "Male";
}
}
[Serializable]
public class Course
{
public string Name;
[Xmlignore]public string Description;
Public Course ()
{
}
Public Course (String name,string description)
{
Name=name;
Description=description;
}
}
Test classes for serialization and deserialization:
Class Test
{
Serialization of
public void Serialiaze ()
{
Person C=new person ("Cyj")
C.courses=new course[2];
C.courses[0]=new Course ("English", "communication Tool")
C.courses[1]=new Course ("number?," natural science ")
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 ();
}
//deserialization
public void deserialize ()
{
XmlSerializer xs=new XmlSerializer (typeof (person));
Stream stream = new FileStream ("C:\\cyj.xml", FileMode.Open, FileAccess.Read, fileshare.readwrite);
Person p= xs. Deserialize (stream);
Console.WriteLine (p.name);
Console.WriteLine (p.age.tostring ());
Console.WriteLine (p.courses.length.tostring ());
Console.read ();
}
}
The document contents of the formatted XML are:
<?xml version= "1.0"?>
<person xmlns:xsd=http://www.w3.org/2001/xmlschema xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" >
<Sex> Men </Sex>
<Age>31</Age>
<Courses>
<Course>
<Name> English </Name>
</Course>
<Course>
<Name> Math </Name>
</Course>
</Courses>
<Name>cyj</Name>
</Person>
Serialization and deserialization of C#xml