1. 程式人生 > >C#語法小知識(十六)序列化與反序列化(XML)

C#語法小知識(十六)序列化與反序列化(XML)

C#提供了兩類序列化與反序列化的手段,一種是XmlSerializer(名稱空間System.Xml.Serialization),另一種我們會在後續文章中介紹(參考C#語法小知識(十七)序列化與反序列化(Binary))。

首先我們定義一個Book類,我們要在程式中對它進行序列化和反序列化:

public class Book
{
	public string title; 
	public int No;
	public Book(string title_, int no_)
	{
		title = title_;
		No = no_;
	}
	public Book()
	{
	}
}

實現序列化和反序列化的方法:
	public void WriteXML()
	{
		Book book = new Book("xml", 1);
		XmlSerializer writer = new XmlSerializer(typeof(Book));
		System.IO.StreamWriter file = new System.IO.StreamWriter(@"xml.xml");
		writer.Serialize(file, book);
		file.Close();
	}
	public void ReadXML()
	{
		XmlSerializer reader = new XmlSerializer(typeof(Book));
		System.IO.StreamReader file = new System.IO.StreamReader(@"xml.xml");
		Book book = reader.Deserialize(file) as Book;

		Console.WriteLine(book.title);
		Console.WriteLine(book.No);

		file.Close();
	}

使用:
		WriteXML ();
		ReadXML ();

列印:

xml

1

如果某些變數不需要序列化,可以為這個變數增加特性XmlIgnore(關於特性參考C#語法小知識(七)特性)。

例如我們在為No變數增加特性:

	[XmlIgnore]
	public int No;

那麼打印出來的結果就是:

xml

0


xml序列化非常易用且好用,而且我們可以看到序列化之後的檔案:

<?xml version="1.0" encoding="utf-8"?>
<Book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <title>xml</title>
</Book>

但是如果要在一個檔案中序列化多個不同類的物件,那麼就會麻煩一點。

例如我們定義了一個Album類:

public class Album
{
	public string owner; 
	public int count;
	public Album(string owner_, int count_)
	{
		owner = owner_;
		count = count_;
	}
	public Album()
	{
	}
}

為了一個檔案中同時序列化Book和Album的例項,我們就需要再額外定義一個包含Book和Album變數的型別:
public class Shelf
{
	public Book book;
	public Album album;
}
定義序列化和反序列化方法:
	public void WriteShelfXML()
	{
		Shelf shelf = new Shelf ();
		shelf.book = new Book ("shelf_xml", 2);
		shelf.album = new Album ("Jessica", 27);
		XmlSerializer writer = new XmlSerializer(typeof(Shelf));
		System.IO.StreamWriter file = new System.IO.StreamWriter(@"shelf_xml.xml");
		writer.Serialize(file, shelf);
		file.Close();
	}
	public void ReadShelfXML()
	{
		XmlSerializer reader = new XmlSerializer(typeof(Shelf));
		System.IO.StreamReader file = new System.IO.StreamReader(@"shelf_xml.xml");
		Shelf shelf = reader.Deserialize(file) as Shelf;

		Console.WriteLine(shelf.book.title);
		Console.WriteLine(shelf.book.No);
		Console.WriteLine(shelf.album.owner);
		Console.WriteLine(shelf.album.count);

		file.Close();
	}

xml檔案:
<?xml version="1.0" encoding="utf-8"?>
<Shelf xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <book>
    <title>shelf_xml</title>
  </book>
  <album>
    <owner>Jessica</owner>
  </album>
</Shelf>