示例,主要包括System.Xml.Serialization命名空間下的XmlRoot、XmlElement、XmlAttribute、XmlText、XmlIgnore等特性的簡單使用,高級使用可自行查看msdn。
實體類代碼:

[XmlRoot("信息")] // 該特性標記為根節點 public class Info { [XmlIgnore] // 此公共屬性不會被序列化 public int Count { get; set; } public Server 服務端 { get; set; } // 不使用標記 [XmlElement("客戶端")] // List<Client> 表示有多個 '客戶端' 節點 public List<Client> Client { get; set; } } public class Server { [XmlAttribute("備注")] // 節點 '服務端' 的一個名為 '備注' 的屬性 public string Note; [XmlText] // 節點 '服務端' 的值 public string Name; } public class Client { [XmlAttribute("名稱")] // 在 '客戶端' 節點添加名為 '名稱' 的屬性 public string Name { get; set; } [XmlElement("地址")] // 節點 '客戶端' 的子節點 public string Adress { get; set; } [XmlElement("端口")] // 節點 '客戶端' 的子節點 public string Port { get; set; } }
實例化代碼:

Info info = new Info { Count = 2, 服務端 = new Server { Name = "用戶服務", Note = "無實際意義" }, Client = new List<Client> { new Client { Name = "測試用戶", Adress = "192.168.1.0", Port = "6666" }, new Client { Name = "軒", Adress = "192.168.1.1", Port = "7777" } } };
序列化結果:
<?xml version="1.0"?> <信息> <服務端 備注="無實際意義">用戶服務</服務端> <客戶端 名稱="測試用戶"> <地址>192.168.1.0</地址> <端口>6666</端口> </客戶端> <客戶端 名稱="軒"> <地址>192.168.1.1</地址> <端口>7777</端口> </客戶端> </信息>
值得一提的是,在實際運用中,自定義命名空間[xmlns:......]的方法是使用XmlSerializer類的重載方法:
public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces);
進行序列化,其中“namespaces”參數可由以下代碼創建:
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(
new[] { new XmlQualifiedName(string.Empty, "") });