XmlSerializer是對xml進行序列化操做的對象。寫了一個Order的序列化方法供留念。ui
序列化針對有get,set的屬性;屬性必須是public方式;對象順序和序列化的順序一致。this
對象定義spa
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Artech.XmlSerializerDemos { public class Order { private double _totalPrice; private Guid _id; public Guid ID { get { return _id; } //set; } private DateTime _date; public DateTime Date { //get; set{_date=value;} } public string Customer { get; set; } public string ShipAddress { get; set; } public Order() { } public Order(double totalPrice) { this._totalPrice = totalPrice; } } }
序列化方法code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; namespace Artech.XmlSerializerDemos { class Program { static void Main(string[] args) { Order order = new Order() { //ID = Guid.NewGuid(), Date = DateTime.Today, Customer = "Foo", ShipAddress = "airport address" }; Serialize<Order>(order, @"E:\Order.xml"); } static void Serialize<T>(T instance, string fileName) { using (XmlWriter writer = new XmlTextWriter(fileName, Encoding.UTF8)) { XmlSerializer serializer = new XmlSerializer(typeof(T)); serializer.Serialize(writer, instance); } } } }