using System ;
using System.IO ;
using System.Xml.Serialization ;
namespace Xml_serial
{
public class Student
{
private string name ;
public string Name //為Name設定屬性
{
get
{
return name ;
}
set
{
name = value ;
}
}
public string Sex ;
public int Age = 30 ;
public Course [ ] Courses ;
public Student ( ) //無參數的建構子
{
}
public Student (string Name) //帶一個參數的建構子
{
name = Name ;
Sex = " Male " ;
}
}
public class Course //無參數的建構子
{
public string Name ;
[XmlIgnore]
public string Description ;//使用[XmlIgnore]表示不生成XML
public Course ( )
{
}
public Course (string name, string description) //帶兩個參數的建構子
{
Name = name ;
Description = description ;
}
}
public class Test
{
public void XMLSerialize ( ) //序列化成XML
{
Student stu = new Student ("小李") ;
stu.Course = new Course [2] ;
stu.Course [0] = new Course ("國文", "語言課") ;
stu.Course [1] = new Course ("英文", "語言課") ;
XmlSerializer x = new XmlSerializer (typeof (Student) ) ;
Stream stream = new FileStream ("c:\\student.xml", FileMode.Create,
FileAccess.Write, FileShare.Read) ;
x.Serialize (stream, stu) ; //執行序列化
stream.Close ( ) ;
}
public void XMLDeserialize ( ) //反序列化 (還原)
{
XmlSerializer x =new XmlSerializer(typeof (Student) ) ;
Stream stream = new FileStream ("c:\\student.xml", FileMode.Open,
FileAccess.Read, FileShare.Read) ;
Student stu = x.Deserialize (stream) as Student ;//執行反序列化
Console.WriltrLine (stu.Age.ToString ( ) ) ;
Console.WriteLine (stu.Courses [0] .Name) ;
Console.WriteLine (stu.Courses [0] .Description) ;
Console.WriteLine (stu.Coruses [1] .Name) ;
Console.WriteLine (stu.Coruses [1] .Description) ;
stream.Close ( ) ;
}
public static void Main ( )
{
Test test = new Test ( ) ;
test.XMLSerialize ( ) ;
test.XMLDeserialize ( ) ;
}
}
}
因為Description變數使用XmlIgnore屬性,所以它的值是null,創見的XML文件也就沒有該節點。
沒有留言:
張貼留言