C# 用XmlSerializer進行序列化和反序列化

和BinaryFormatter序列化一樣,做一個可以序列化的類Person:

namespace Serializable
{
    [Serializable] //不可少! 
    public class Person
    {
        private String name;
        private String sex;
        private int age;

        public Person() //XmlSerializer序列化要求一定要有無參數構造函數 
        {
            name = "";
            sex = "";
            age = 0;
        }

        public Person(String n, String s, int a)
        {
            name = n;
            sex = s;
            age = a;
        }

        public String Name
        {
            get 
            {
                return name;
            }
            set 
            {
                name = value;
            }
        }

        public String Sex
        {
            get
            {
                return sex;
            }
            set
            {
                sex = value;
            }
        }

        public int Age
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
            }
        }
    }
}

 

//主運行程序

namespace Serializable
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person("張三", "男", 20);
            //序列化
            try
            {
                FileStream fs = new FileStream("serialiable.xml", FileMode.Create);
                XmlSerializer xs = new XmlSerializer(typeof(Person));
                xs.Serialize(fs, p1);
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("序列化成功!");

            Console.Read();

            //反序列化
            try
            {
                FileStream fs = new FileStream("serialiable.xml", FileMode.Open, FileAccess.Read);
                XmlSerializer xs = new XmlSerializer(typeof(Person));
                Person p = (Person)xs.Deserialize(fs);
                Console.WriteLine(p.Name + p.Sex + p.Age);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.Read();
            Console.Read();
        }
    }
}

 

結果圖:

 

生成的XML文件:

  1. 這篇隨筆對應的.Net命名空間是System.Xml.Serialization;文中的示例代碼需要引用這個命名空間。
  2. 爲什麼要做序列化和反序列化?
  3. .Net程序執行時,對象都駐留在內存中;內存中的對象如果需要傳遞給其他系統使用;或者在關機時需要保存下來以便下次再次啓動程序使用就需要序列化和反序列化。
  4. 範圍:本文只介紹xml序列化,其實序列化可以是二進制的序列化,也可以是其他格式的序列化。
  5. 看一段最簡單的Xml序列化代碼
  6. class Program
  7. {
  8.     static void Main(string[] args)
  9.     {
  10.         int i = 10;
  11.         //聲明Xml序列化對象實例serializer
  12.         XmlSerializer serializer = new XmlSerializer(typeof(int));
  13.         //執行序列化並將序列化結果輸出到控制檯
  14.         serializer.Serialize(Console.Out, i);
  15.         Console.Read();
  16.     }
  17. }
  18. 上面代碼對int i進行了序列化,並將序列化的結果輸出到了控制檯,輸出結果如下
  19. <?xml version="1.0" encoding="gb2312"?>
  20. <int>10</int>
  21. 可以將上述序列化的xml進行反序列化,如下代碼
  22. static void Main(string[] args)
  23. {
  24.     using (StringReader rdr = new StringReader(@"<?xml version=""1.0"" encoding=""gb2312""?>
  25. <int>10</int>"))
  26.     {
  27.         //聲明序列化對象實例serializer
  28.         XmlSerializer serializer = new XmlSerializer(typeof(int));
  29.         //反序列化,並將反序列化結果值賦給變量i
  30.         int i = (int)serializer.Deserialize(rdr);
  31.         //輸出反序列化結果
  32.         Console.WriteLine("i = " + i);
  33.         Console.Read();
  34.     }
  35. }
  36. 以上代碼用最簡單的方式說明了xml序列化和反序列化的過程,.Net系統類庫爲我們做了大量的工作,序列化和反序列化都非常簡單。但是在現實中業務需求往往比較複雜,不可能只簡單的序列化一個int變量,顯示中我們需要對複雜類型進行可控制的序列化。
  37. 自定義對象的Xml序列化:
  38. System.Xml.Serialization命名空間中有一系列的特性類,用來控制複雜類型序列化的控制。例如XmlElementAttribute、XmlAttributeAttribute、XmlArrayAttribute、XmlArrayItemAttribute、XmlRootAttribute等等。
  39. 看一個小例子,有一個自定義類Cat,Cat類有三個屬性分別爲Color,Saying,Speed。
  40. namespace UseXmlSerialization
  41. {
  42.     class Program
  43.     {
  44.         static void Main(string[] args)
  45.         {
  46.             //聲明一個貓咪對象
  47.             var c = new Cat { Color = "White", Speed = 10, Saying = "White or black,  so long as the cat can catch mice,  it is a good cat" };
  48.  
  49.             //序列化這個對象
  50.             XmlSerializer serializer = new XmlSerializer(typeof(Cat));
  51.  
  52.             //將對象序列化輸出到控制檯
  53.             serializer.Serialize(Console.Out, c);
  54.  
  55.             Console.Read();
  56.         }
  57.     }
  58.  
  59.     [XmlRoot("cat")]
  60.     public class Cat
  61.     {
  62.         //定義Color屬性的序列化爲cat節點的屬性
  63.         [XmlAttribute("color")]
  64.         public string Color { get; set; }
  65.  
  66.         //要求不序列化Speed屬性
  67.         [XmlIgnore]
  68.         public int Speed { get; set; }
  69.  
  70.         //設置Saying屬性序列化爲Xml子元素
  71.         [XmlElement("saying")]
  72.         public string Saying { get; set; }
  73.     }
  74. }
  75. 可以使用XmlElement指定屬性序列化爲子節點(默認情況會序列化爲子節點);或者使用XmlAttribute特性制定屬性序列化爲Xml節點的屬性;還可以通過XmlIgnore特性修飾要求序列化程序不序列化修飾屬性。
  76. 對象數組的Xml序列化:
  77. 數組的Xml序列化需要使用XmlArrayAttribute和XmlArrayItemAttribute;XmlArrayAttribute指定數組元素的Xml節點名,XmlArrayItemAttribute指定數組元素的Xml節點名。
  78. 如下代碼示例:
  79. using System;
  80. using System.Collections.Generic;
  81. using System.Linq;
  82. using System.Text;
  83. using System.Xml.Serialization;
  84.  
  85. namespace UseXmlSerialization
  86. {
  87.     class Program
  88.     {
  89.         static void Main(string[] args)
  90.         {
  91.             //聲明一個貓咪對象
  92.             var cWhite = new Cat { Color = "White", Speed = 10, Saying = "White or black,  so long as the cat can catch mice,  it is a good cat" };
  93.             var cBlack = new Cat { Color = "Black", Speed = 10, Saying = "White or black,  so long as the cat can catch mice,  it is a good cat" };
  94.  
  95.             CatCollection cc = new CatCollection { Cats = new Cat[] { cWhite,cBlack} };
  96.  
  97.             //序列化這個對象
  98.             XmlSerializer serializer = new XmlSerializer(typeof(CatCollection));
  99.  
  100.             //將對象序列化輸出到控制檯
  101.             serializer.Serialize(Console.Out, cc);
  102.  
  103.             Console.Read();
  104.         }
  105.     }
  106.  
  107.     [XmlRoot("cats")]
  108.     public class CatCollection
  109.     {
  110.         [XmlArray("items"),XmlArrayItem("item")]
  111.         public Cat[] Cats { get; set; }
  112.     }
  113.  
  114.     [XmlRoot("cat")]
  115.     public class Cat
  116.     {
  117.         //定義Color屬性的序列化爲cat節點的屬性
  118.         [XmlAttribute("color")]
  119.         public string Color { get; set; }
  120.  
  121.         //要求不序列化Speed屬性
  122.         [XmlIgnore]
  123.         public int Speed { get; set; }
  124.  
  125.         //設置Saying屬性序列化爲Xml子元素
  126.         [XmlElement("saying")]
  127.         public string Saying { get; set; }
  128.     }
  129. }
  130. 以上代碼將輸出:
  131. <?xml version="1.0" encoding="gb2312"?>
  132. <cats xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://ww
  133. w.w3.org/2001/XMLSchema">
  134.   <items>
  135.     <item color="White">
  136.       <saying>White or black,  so long as the cat can catch mice,  it is a good
  137. cat</saying>
  138.     </item>
  139.     <item color="Black">
  140.       <saying>White or black,  so long as the cat can catch mice,  it is a good
  141. cat</saying>
  142.     </item>
  143.   </items>
  144. </cats>
  145. XmlSerializer內存泄漏問題:
  146. 仔細看了下msdn,確實存在泄漏的情況,msdn說明如下:
  147. 動態生成的程序集
  148. 爲了提高性能,XML 序列化基礎結構將動態生成程序集,以序列化和反序列化指定類型。此基礎結構將查找並重複使用這些程序集。此行爲僅在使用以下構造函數時發生:
  149. XmlSerializer(Type)
  150. XmlSerializer.XmlSerializer(Type, String)
  151. 如果使用任何其他構造函數,則會生成同一程序集的多個版本,且絕不會被卸載,這將導致內存泄漏和性能降低。最簡單的解決方案是使用先前提到的兩個構造函數的其中一個。否則,必須在 Hashtable 中緩存程序集,如以下示例中所示。
  152. 也就是說我們在使用XmlSerializer序列化,初始化XmlSerializer對象時最好使用下面兩個構造函數否則會引起內存泄漏。
  153. XmlSerializer(Type)
  154. XmlSerializer.XmlSerializer(Type, String)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章