zoukankan      html  css  js  c++  java
  • XML 序列化和反序列化详例代码

      这是一个使用序列化和反序列化的详细例子来操作复杂的XML数据,其中还举例数组和List的使用方法和区别。 

      1
      2using System.Xml;
      3using System.Xml.Serialization;
      4using System.IO;
      5
      6namespace SerializableTest
      7{
      8    
      9
     10    // The XmlRootAttribute allows you to set an alternate name 
     11    // (PurchaseOrder) for the XML element and its namespace. By 
     12    // default, the XmlSerializer uses the class name. The attribute 
     13    // also allows you to set the XML namespace for the element. Lastly,
     14    // the attribute sets the IsNullable property, which specifies whether 
     15    // the xsi:null attribute appears if the class instance is set to 
     16    // a null reference.
     17    
     18    
     19    //[XmlRootAttribute("PurchaseOrder", Namespace = "http://www.cpandl.com", IsNullable = false)]
     20    [XmlRootAttribute("PurchaseOrder")]
     21    [XmlInclude(typeof(OrderedItem))]
     22    public class PurchaseOrder
     23    {
     24        public Address ShipTo;
     25        public string OrderDate;
     26        
     27        // The XmlArrayAttribute changes the XML element name
     28        // from the default of "OrderedItems" to "Items".
     29        [XmlArrayAttribute("Items")]
     30        public OrderedItem[] OrderedItems;        
     31        [XmlArrayAttribute("Items2")]
     32        public List<OrderedItem> OrderedItemList;
     33        
     34        public decimal SubTotal;
     35        public decimal ShipCost;
     36        public decimal TotalCost;
     37    }

     38
     39    public class Address
     40    {
     41        // The XmlAttribute instructs the XmlSerializer to serialize the 
     42        // Name field as an XML attribute instead of an XML element (the 
     43        // default behavior).
     44        [XmlAttribute]
     45        public string Name;
     46        public string Line1;
     47
     48        // Setting the IsNullable property to false instructs the 
     49        // XmlSerializer that the XML attribute will not appear if 
     50        // the City field is set to a null reference.
     51        [XmlElementAttribute(IsNullable = false)]
     52        public string City;
     53        public string State;
     54        public string Zip;
     55    }

     56
     57    public class OrderedItem
     58    {
     59        [XmlAttribute("Name")]
     60        public string ItemName;
     61        public string Description;
     62        public decimal UnitPrice;
     63        public int Quantity;
     64        public decimal LineTotal;
     65
     66        // Calculate is a custom method that calculates the price per item
     67        // and stores the value in a field.
     68        public void Calculate()
     69        {
     70            LineTotal = UnitPrice * Quantity;
     71        }

     72    }

     73
     74    public class Test
     75    {
     76        public static void Main()
     77        {
     78            // Read and write purchase orders.
     79            Test t = new Test();
     80            t.CreatePO("po.xml");
     81            t.ReadPO("po.xml");
     82            Console.Read();
     83        }

     84
     85        private void CreatePO(string filename)
     86        {
     87            // Creates an instance of the XmlSerializer class;
     88            // specifies the type of object to serialize.
     89            XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
     90            TextWriter writer = new StreamWriter(filename);
     91            PurchaseOrder po = new PurchaseOrder();
     92
     93            // Creates an address to ship and bill to.
     94            Address billAddress = new Address();
     95            billAddress.Name = "Teresa Atkinson";
     96            billAddress.Line1 = "1 Main St.";
     97            billAddress.City = "AnyTown";
     98            billAddress.State = "WA";
     99            billAddress.Zip = "00000";
    100            // Sets ShipTo and BillTo to the same addressee.
    101            po.ShipTo = billAddress;
    102            po.OrderDate = System.DateTime.Now.ToLongDateString();
    103
    104            // Creates an OrderedItem.
    105            OrderedItem i1 = new OrderedItem();
    106            i1.ItemName = "Widget S_1";
    107            i1.Description = "Small widget";
    108            i1.UnitPrice = (decimal)5.23;
    109            i1.Quantity = 3;
    110            i1.Calculate();
    111
    112            // Creates an OrderedItem.
    113            OrderedItem i2 = new OrderedItem();
    114            i2.ItemName = "Widget S_2";
    115            i2.Description = "Small widget_2";
    116            i2.UnitPrice = (decimal)25.23;
    117            i2.Quantity = 3;
    118            i2.Calculate();
    119
    120            // Inserts the item into the array.           
    121            OrderedItem[] items = { i1,i2 };
    122
    123            po.OrderedItemList = new List<OrderedItem>();
    124            po.OrderedItemList.Add(i1);
    125            po.OrderedItemList.Add(i2);
    126
    127            po.OrderedItems = items;
    128            // Calculate the total cost.
    129            decimal subTotal = new decimal();
    130            foreach (OrderedItem oi in items)
    131            {
    132                subTotal += oi.LineTotal;
    133            }

    134            po.SubTotal = subTotal;
    135            po.ShipCost = (decimal)12.51;
    136            po.TotalCost = po.SubTotal + po.ShipCost;
    137            // Serializes the purchase order, and closes the TextWriter.
    138            serializer.Serialize(writer, po);
    139            writer.Close();
    140        }

    141
    142        protected void ReadPO(string filename)
    143        {
    144            // Creates an instance of the XmlSerializer class;
    145            // specifies the type of object to be deserialized.
    146            XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
    147            // If the XML document has been altered with unknown 
    148            // nodes or attributes, handles them with the 
    149            // UnknownNode and UnknownAttribute events.
    150            serializer.UnknownNode += new
    151            XmlNodeEventHandler(serializer_UnknownNode);
    152            serializer.UnknownAttribute += new
    153            XmlAttributeEventHandler(serializer_UnknownAttribute);
    154
    155            // A FileStream is needed to read the XML document.
    156            FileStream fs = new FileStream(filename, FileMode.Open);
    157            // Declares an object variable of the type to be deserialized.
    158            PurchaseOrder po;
    159            // Uses the Deserialize method to restore the object's state 
    160            // with data from the XML document. */
    161            po = (PurchaseOrder)serializer.Deserialize(fs);
    162            // Reads the order date.
    163            Console.WriteLine("OrderDate: " + po.OrderDate);
    164
    165            // Reads the shipping address.
    166            Address shipTo = po.ShipTo;
    167            ReadAddress(shipTo, "Ship To:");
    168            // Reads the list of ordered items.
    169            OrderedItem[] items = po.OrderedItems;
    170            Console.WriteLine("Items to be shipped:");
    171            foreach (OrderedItem oi in items)
    172            {
    173                Console.WriteLine("\t" +
    174                oi.ItemName + "\t" +
    175                oi.Description + "\t" +
    176                oi.UnitPrice + "\t" +
    177                oi.Quantity + "\t" +
    178                oi.LineTotal);
    179            }

    180            // Reads the subtotal, shipping cost, and total cost.
    181            Console.WriteLine(
    182            "\n\t\t\t\t\t Subtotal\t" + po.SubTotal +
    183            "\n\t\t\t\t\t Shipping\t" + po.ShipCost +
    184            "\n\t\t\t\t\t Total\t\t" + po.TotalCost
    185            );
    186        }

    187
    188        protected void ReadAddress(Address a, string label)
    189        {
    190            // Reads the fields of the Address.
    191            Console.WriteLine(label);
    192            Console.Write("\t" +
    193            a.Name + "\n\t" +
    194            a.Line1 + "\n\t" +
    195            a.City + "\t" +
    196            a.State + "\n\t" +
    197            a.Zip + "\n");
    198        }

    199
    200        protected void serializer_UnknownNode
    201        (object sender, XmlNodeEventArgs e)
    202        {
    203            Console.WriteLine("Unknown Node:" + e.Name + "\t" + e.Text);
    204        }

    205
    206        protected void serializer_UnknownAttribute
    207        (object sender, XmlAttributeEventArgs e)
    208        {
    209            System.Xml.XmlAttribute attr = e.Attr;
    210            Console.WriteLine("Unknown attribute " +
    211            attr.Name + "='" + attr.Value + "'");
    212        }

    213    }

    214}

    215
  • 相关阅读:
    Java实现 蓝桥杯VIP 算法训练 字符串逆序
    Java实现 蓝桥杯VIP 算法训练 字符串逆序
    Java实现 蓝桥杯VIP 算法训练 最长字符串
    Java实现 蓝桥杯VIP 算法训练 最长字符串
    Java实现 蓝桥杯VIP 算法训练 最长字符串
    Java实现 蓝桥杯VIP 算法训练 最长字符串
    Java实现 蓝桥杯VIP 算法训练 最长字符串
    Java实现 蓝桥杯VIP 算法训练 成绩的等级输出
    Java实现 蓝桥杯VIP 算法训练 成绩的等级输出
    Qt 自定义model实现文件系统的文件名排序
  • 原文地址:https://www.cnblogs.com/digjim/p/1379687.html
Copyright © 2011-2022 走看看