XmlSerializer

一、写三个类

PurchaseOrder.cs

    [XmlRootAttribute("PurchaseOrder")]
    public class PurchaseOrder
    {
        public Address ShipTo;
        public string OrderDate;
        // The XmlArrayAttribute changes the XML element name
        // from the default of "OrderedItems" to "Items".
        [XmlArrayAttribute("Items1")]
        public OrderedItem[] OrderedItems;
        public decimal SubTotal;
        public decimal ShipCost;
        public decimal TotalCost;
        private List<OrderedItem> Items2 = new List<OrderedItem>();
        public List<OrderedItem> Transducers
        {
            get
            {
                return Items2;
            }
            set
            {
                Items2 = value;
            }
        }
    }

Address.cs

 public class Address
    {
        // The XmlAttribute instructs the XmlSerializer to serialize the
        // Name field as an XML attribute instead of an XML element (the
        // default behavior).
        [XmlAttribute]
        public string Name;
        public string Line1;

        // Setting the IsNullable property to false instructs the
        // XmlSerializer that the XML attribute will not appear if
        // the City field is set to a null reference.
        [XmlElementAttribute(IsNullable = false)]
        public string City;
        public string State;
        public string Zip;
    }

 OrderedItem.cs 

public class OrderedItem
    {
        public string ItemName;
        public string Description;
        public decimal UnitPrice;
        public int Quantity;
        public decimal LineTotal;

        // Calculate is a custom method that calculates the price per item
        // and stores the value in a field.
        public void Calculate()
        {
            LineTotal = UnitPrice * Quantity;
        }
    }

二、建立一个web页面

WebForm1.aspx.cs

 

 public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            CreatePO("C:/po.xml");
        }
        private void CreatePO(string filename)
        {
            // Creates an instance of the XmlSerializer class;
            // specifies the type of object to serialize.
            XmlSerializer serializer =new XmlSerializer(typeof(PurchaseOrder));
            TextWriter writer = new StreamWriter(filename);
            PurchaseOrder po = new PurchaseOrder();

            // Creates an address to ship and bill to.
            Address billAddress = new Address();
            billAddress.Name = "Teresa Atkinson";
            billAddress.Line1 = "1 Main St.";
            billAddress.City = "AnyTown";
            billAddress.State = "WA";
            billAddress.Zip = "00000";
            // Sets ShipTo and BillTo to the same addressee.
            po.ShipTo = billAddress;
            po.OrderDate = System.DateTime.Now.ToLongDateString();

            // Creates an OrderedItem.
            OrderedItem i1 = new OrderedItem();
            i1.ItemName = "Widget S";
            i1.Description = "Small widget";
            i1.UnitPrice = (decimal)5.23;
            i1.Quantity = 3;
            i1.Calculate();
            //------------
            po.Transducers.Add(i1);
            //------------
            // Inserts the item into the array.
            OrderedItem[] items = { i1,i1 };
            po.OrderedItems = items;
            // Calculate the total cost.
            decimal subTotal = new decimal();
            foreach (OrderedItem oi in items)
            {
                subTotal += oi.LineTotal;
            }
            po.SubTotal = subTotal;
            po.ShipCost = (decimal)12.51;
            po.TotalCost = po.SubTotal + po.ShipCost;
            // Serializes the purchase order, and closes the TextWriter.
            serializer.Serialize(writer, po);
            writer.Close();
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            ReadPO("C:/po.xml");
        }
        protected void ReadPO(string filename)
        {
            // Creates an instance of the XmlSerializer class;
            // specifies the type of object to be deserialized.
            XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
            // If the XML document has been altered with unknown
            // nodes or attributes, handles them with the
            // UnknownNode and UnknownAttribute events.
            serializer.UnknownNode += new XmlNodeEventHandler(serializer_UnknownNode);
            serializer.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);

            // A FileStream is needed to read the XML document.
            FileStream fs = new FileStream(filename, FileMode.Open);
            // Declares an object variable of the type to be deserialized.
            PurchaseOrder po;
            // Uses the Deserialize method to restore the object's state
            // with data from the XML document. */
            po = (PurchaseOrder)serializer.Deserialize(fs);


            // Reads the order date.
            Response.Write("OrderDate: " + po.OrderDate+"<br/>");
           // Console.WriteLine("OrderDate: " + po.OrderDate);

            // Reads the shipping address.
            Address shipTo = po.ShipTo;
            ReadAddress(shipTo, "Ship To:");
            // Reads the list of ordered items.
            OrderedItem[] items = po.OrderedItems;
            Response.Write("Items to be shipped:"+"<br/>");
            foreach (OrderedItem oi in items)
            {
                Response.Write("\t" +
                oi.ItemName + "\t" +
                oi.Description + "\t" +
                oi.UnitPrice + "\t" +
                oi.Quantity + "\t" +
                oi.LineTotal + "<br/>");
            }
            // Reads the subtotal, shipping cost, and total cost.
            Response.Write(
            "\n\t\t\t\t\t Subtotal\t" + po.SubTotal +
            "\n\t\t\t\t\t Shipping\t" + po.ShipCost +
            "\n\t\t\t\t\t Total\t\t" + po.TotalCost+"<br/>"
            );

            //------------

            foreach (OrderedItem oi in po.Transducers)
            {
                Response.Write("\t" +
                oi.ItemName + "\t" +
                oi.Description + "\t" +
                oi.UnitPrice + "\t" +
                oi.Quantity + "\t" +
                oi.LineTotal + "<br/>");
            }
            //------------
        }


        protected void ReadAddress(Address a, string label)
        {
            // Reads the fields of the Address.
            Response.Write(label);
            Response.Write("\t" +
            a.Name + "\n\t" +
            a.Line1 + "\n\t" +
            a.City + "\t" +
            a.State + "\n\t" +
            a.Zip + "\n" + "<br/>");
        }

        protected void serializer_UnknownNode(object sender, XmlNodeEventArgs e)
        {
            Response.Write("Unknown Node:" + e.Name + "\t" + e.Text+"<br/>");
        }

        protected void serializer_UnknownAttribute(object sender, XmlAttributeEventArgs e)
        {
            System.Xml.XmlAttribute attr = e.Attr;
            Response.Write("Unknown attribute " + attr.Name + "='" + attr.Value + "'" + "<br/>");
        }


    }

posted on 2009-01-09 10:26  张林春  阅读(789)  评论(0编辑  收藏  举报