日期:2014-05-18  浏览次数:20541 次

XMLSerializer怎样序列化这个类啊
以下有两个类,其中CartItem类的数组是ShoppingCart类的一个公共字段,请问怎样使用XMLSerializer序列化ShoppingCart类啊
public class ShoppingCart
{
  public string UserName;
  public string CreditCardNumber;
  public CartItem[] CartItems;
public ShoppingCart()
{
}
}

public class CartItem
{
  public string ProductName;
  public decimal ProductPrice;
public CartItem(string productName,decimal productPrice)
{
  this.ProductName = productName;
  this.ProductPrice = productPrice;
}
}



------解决方案--------------------
C# code

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()
        { }
    } 
}