带List的类的序列化实例

Product类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace XmlSerialization
{
    
    //[XmlRoot(ElementName = "Product")]
    public class Product
    {
        private int prodId;
        private string prodName;
        private int suppId;
        private int catId;
        private string qtyPerUnit;
        private decimal unitPrice;
        private short unitsInStock;
        private short unitsOnOrder;
        private short reorderLvl;
        private bool discont;
        private int disc;
        //[XmlElementAttribute()]
        //[XmlAttributeAttribute(AttributeName = "Discount")]
        //[XmlAttributeAttribute()]
        public int Discount
        {
            get { return disc; }
            set { disc = value; }
        }
        [XmlElementAttribute()]
        public int ProductID
        {
            get { return prodId; }
            set { prodId = value; }
        }
        [XmlElementAttribute()]
        public string ProductName
        {
            get { return prodName; }
            set { prodName = value; }
        }
        [XmlElementAttribute()]
        public int SupperlierID
        {
            get { return suppId; }
            set { suppId = value; }
        }
        [XmlElementAttribute()]
        public string QuantityPerUnit
        {
            get { return qtyPerUnit; }
            set { qtyPerUnit = value; }
        }
        [XmlElementAttribute()]
        public decimal UnitPrice
        {
            get { return unitPrice; }
            set { unitPrice = value; }
        }
        [XmlElementAttribute()]
        public short UnitsInStock
        {
            get { return unitsInStock; }
            set { unitsInStock = value; }
        }
        [XmlElementAttribute()]
        public short UnitsOnOrder
        {
            get { return unitsOnOrder; }
            set { unitsOnOrder = value; }
        }
        [XmlElementAttribute()]
        public short ReorderLevel
        {
            get { return reorderLvl; }
            set { reorderLvl = value; }
        }
        [XmlElementAttribute()]
        public bool Discontinued
        {
            get { return discont; }
            set { discont = value; }
        }
        [XmlIgnore]
        public int CategoryID
        {
            get { return catId; }
            set { catId = value; }
        }
        public override string ToString()
        {
            StringBuilder outText = new StringBuilder();
            outText.Append(prodId);
            outText.Append("\r\n");
            outText.Append(prodName);
            outText.Append("\r\n");
            outText.Append(unitPrice);
            return outText.ToString();
        }
       
    }
}

BookProduct 类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace XmlSerialization
{
    //[XmlRoot(ElementName = "BookProduct")]
    public class BookProduct:Product
    {
        private string isbnNum;
        public string ISBN
        {
            get { return isbnNum; }
            set { isbnNum = value; }
        }
        public BookProduct() { }
    }
}

Inventory类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.ObjectModel;
namespace XmlSerialization
{
    public class Inventory
    {
        private ObservableCollection<Product> stuff;
        public Inventory()
        {

        }
        [XmlArrayItem("Product", typeof(Product)),
            XmlArrayItem("BookProduct", typeof(BookProduct))] //必须声明list的elementnode名称
        public ObservableCollection<Product> InventoryItems
        {
            get { return stuff; }
            set { stuff = value; }
        }
        
        public  Product  GetProduct(string prodName)
        {
            Product prod = null;
            try
            {
                prod = InventoryItems.Where(p => p.ProductName == prodName).Single();
            }
            catch
            {

            }
           
            return prod;
        }
         public bool Contains(Product prod)
        {
            if (prod == null)
                return false;
            if (InventoryItems.Where(p => p.ProductID == prod.ProductID).Count<Product>() > 0)
                return true;
            else
                return false;
        }
        public override string ToString()
        {
            StringBuilder outText = new StringBuilder();
            foreach(Product prod in stuff)
            {
                outText.Append(prod.ProductName);
                outText.Append("\r\n");
            }
            return outText.ToString();
        }
    }
}

序列化 Inventory

private void cmdSerialize1_Click(object sender, RoutedEventArgs e)
        {
            Product newpd = new Product();
            BookProduct newBook = new BookProduct();
            newpd.ProductID = 100;
            newpd.ProductName = "Product Thing";
            newpd.SupperlierID = 10;
            newpd.CategoryID = 12;

            newBook.ProductID = 101;
            newBook.ProductName = "How to Use Your New Product Thing";
            newBook.SupperlierID = 10;
            newBook.ISBN = "123";
            newBook.CategoryID = 12;
            ObservableCollection<Product> products = new ObservableCollection<Product>();
            products.Add(newpd);
            products.Add(newBook);
            Inventory inv = new Inventory();
            inv.InventoryItems = products;
            TextWriter tw = new StreamWriter("order.xml");
            XmlSerializer sr = new XmlSerializer(typeof(Inventory));
            sr.Serialize(tw, inv);
            tw.Close();
            webBrower.Navigate(AppDomain.CurrentDomain.BaseDirectory + "order.xml");
        }

修改elementnote后序列化

private void cmdSerialize2_Click_(object sender, RoutedEventArgs e)
        {
            XmlAttributes attrs = new XmlAttributes();
            attrs.XmlElements.Add(new XmlElementAttribute("Book", typeof(BookProduct)));
            attrs.XmlElements.Add(new XmlElementAttribute("Product", typeof(Product)));
            XmlAttributeOverrides attrOver = new XmlAttributeOverrides();
            attrOver.Add(typeof(Inventory), "InventoryItems", attrs);

            Product newProd = new Product();
            BookProduct newBook = new BookProduct();
            newProd.ProductID = 100;
            newProd.ProductName = "Product Thing";
            newProd.SupperlierID = 10;

            newBook.ProductID = 101;
            newBook.ProductName = "How to Use Your New Product Thing";
            newBook.SupperlierID = 10;
            newBook.ISBN = "123";
            ObservableCollection<Product> Products = new ObservableCollection<Product>();
            Products.Add(newProd);
            Products.Add(newBook);

            Inventory inv = new Inventory();
            inv.InventoryItems = Products;
            TextWriter tr = new StreamWriter("inventory.xml");
            XmlSerializer sr = new XmlSerializer(typeof(Inventory), attrOver);

            sr.Serialize(tr, inv);            
            tr.Close();
            webBrower.Navigate(AppDomain.CurrentDomain.BaseDirectory + "inventory.xml");
           
        }

反序列化Product

 private void cmdDeserialize1_Click(object sender, RoutedEventArgs e)
        {
            Product newProd;
            FileStream f = new FileStream("serialprod.xml", FileMode.Open);
            XmlSerializer newSr = new XmlSerializer(typeof(Product));
            newProd = (Product)newSr.Deserialize(f);
            f.Close();
            MessageBox.Show(newProd.ToString(), "ProductInfo");
            int i = newProd.CategoryID;

        }

反序列化Inventory

 private void cmdDeserialize2_Click(object sender, RoutedEventArgs e)
        {
            Inventory inv;
            FileStream f = new FileStream("order.xml", FileMode.Open);
            XmlSerializer newSr = new XmlSerializer(typeof(Inventory));
            inv = (Inventory)newSr.Deserialize(f);
            f.Close();
            MessageBox.Show(inv.ToString(), "ProductInfo");
            //foreach(Product prod in inv.InventoryItems)
            //{
            //    if(prod.GetType()==typeof(BookProduct))
            //    {
            //        BookProduct bookProd = prod as BookProduct;
            //    } 
            //}
            Product prod = inv.GetProduct("Product Thing");
            if(inv.Contains(prod))
            {
                MessageBox.Show("Has Data");
            }
            if(prod!=null)
                MessageBox.Show(prod.ToString());
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fwsylin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值