日期:2014-05-18 浏览次数:20546 次
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml; using System.Xml.Serialization; namespace XMLSerializer { class Program { static void Main(string[] args) { CartItem[] items = new CartItem[]{new CartItem("商品1",123.45m),new CartItem("商品2",678.90m)}; ShoppingCart cart = new ShoppingCart(); cart.UserName = "jeremyyang"; cart.CreditCardNumber = "secret"; cart.CartItems = items; XmlSerializer serializer = new XmlSerializer(typeof(XMLSerializer.ShoppingCart)); TextWriter writer = new StreamWriter(@"D:\123.xml"); serializer.Serialize(writer, cart); writer.Close(); } } [System.Xml.Serialization.XmlTypeAttribute] [System.Xml.Serialization.XmlRootAttribute] public class ShoppingCart { [XmlElement] public string UserName; [XmlElement] public string CreditCardNumber; [XmlArrayItem] public CartItem[] CartItems; public ShoppingCart() { } } [System.Xml.Serialization.XmlTypeAttribute] public class CartItem { [XmlAttribute] public string ProductName; [XmlAttribute] public decimal ProductPrice; public CartItem(string productName, decimal productPrice) { this.ProductName = productName; this.ProductPrice = productPrice; } //注意 XmlSerializer 必须要有个无参的构造函数 public CartItem() { } } }