CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 187

187

Chương 5: XML

tuần tự hóa đối tượng thành tài liệu XML, giải tuần tự hóa tài liệu thành đối tượng, và rồi hiển
thị tài liệu này:

using System;

using System.Xml;

using System.Xml.Serialization;

using System.IO;

public class SerializeXml {

private static void Main() {

// Tạo danh mục sản phẩm.

ProductCatalog catalog = new ProductCatalog("New Catalog",

DateTime.Now.AddYears(1));

Product[] products = new Product[2];

products[0] = new Product("Product 1", 42.99m);

products[1] = new Product("Product 2", 202.99m);

catalog.Products = products;

// Tuần tự hóa danh mục ra file.

XmlSerializer serializer =

new XmlSerializer(typeof(ProductCatalog));

FileStream fs =

new FileStream("ProductCatalog.xml", FileMode.Create);

serializer.Serialize(fs, catalog);

fs.Close();

catalog = null;

// Giải tuần tự hóa danh mục từ file.

fs = new FileStream("ProductCatalog.xml", FileMode.Open);

catalog = (ProductCatalog)serializer.Deserialize(fs);

// Tuần tự hóa danh mục ra cửa sổ Console.

serializer.Serialize(Console.Out, catalog);

Console.ReadLine();

}