c# XML序列化与反序列化

来源:互联网 发布:地区数据库 编辑:程序博客网 时间:2024/05/16 07:06
[html] view plaincopy
  1. 原先一直用BinaryFormatter来序列化挺好,可是最近发现在WinCE下是没有办法进行BinaryFormatter操作,很不爽,只能改成了BinaryWriter和BinaryReader来读写,突然想到能不能用XML来序列化?于是在网上查了些资料便写了些实践性代码,做些记录,避免以后忘记。  
  2.   
  3. 序列化对象  
  4.   
  5.     public class People  
  6.     {  
  7.         [XmlAttribute("NAME")]  
  8.         public string Name  
  9.         { set; get; }  
  10.         [XmlAttribute("AGE")]  
  11.         public int Age  
  12.         { set; get; }  
  13.     }  
  14.     [XmlRoot("Root")]  
  15.     public class Student : People  
  16.     {  
  17.         [XmlElement("CLASS")]  
  18.         public string Class  
  19.         { set; get; }  
  20.         [XmlElement("NUMBER")]  
  21.         public int Number  
  22.         { set; get; }  
  23.     }  
  24.   
  25. void Main(string[] args)  
  26.   
  27. {  
  28.   
  29.             Student stu = new Student()  
  30.             {  
  31.                 Age = 10,  
  32.                 Class = "Class One",  
  33.                 Name = "Tom",  
  34.                 Number = 1  
  35.             };  
  36.             XmlSerializer ser = new XmlSerializer(typeof(Student));  
  37.             ser.Serialize(File.Create("C:\\x.xml"), stu);  
  38.   
  39. }  
  40.   
  41. 反序列化对象  
  42.   
  43.             XmlSerializer ser = new XmlSerializer(typeof(Student));  
  44.             Student stu = ser.Deserialize(File.OpenRead("C:\\x.xml")) as Student;  
  45.   
  46. 对象数组序列化  
  47.   
  48.     public class People  
  49.     {  
  50.         [XmlAttribute("NAME")]  
  51.         public string Name  
  52.         { set; get; }  
  53.         [XmlAttribute("AGE")]  
  54.         public int Age  
  55.         { set; get; }  
  56.     }  
  57.     [XmlRoot("Root")]  
  58.     public class Student : People  
  59.     {  
  60.         [XmlElement("CLASS")]  
  61.         public string Class  
  62.         { set; get; }  
  63.         [XmlElement("NUMBER")]  
  64.         public int Number  
  65.         { set; get; }  
  66.     }  
  67.   
  68. void Main(string[] args)  
  69.   
  70. {  
  71.   
  72.             List<Student> stuList = new List<Student>();  
  73.             stuList.Add(new Student() { Age = 10Number = 1Name = "Tom"Class = "Class One" });  
  74.             stuList.Add(new Student() { Age = 11Number = 2Name = "Jay"Class = "Class Two" });  
  75.             stuList.Add(new Student() { Age = 12Number = 3Name = "Pet"Class = "Class One" });  
  76.             stuList.Add(new Student() { Age = 13Number = 4Name = "May"Class = "Class Three" });  
  77.             stuList.Add(new Student() { Age = 14Number = 5Name = "Soy"Class = "Class Two" });  
  78.             XmlSerializer ser = new XmlSerializer(typeof(List<Student>));  
  79.             ser.Serialize(File.Create("C:\\x.xml"), stuList);  
  80.   
  81. }  
  82.   
  83. 对象数组反序列  
  84.   
  85.             XmlSerializer ser = new XmlSerializer(typeof(List<Student>));  
  86.             List<Student> stuList = ser.Deserialize(File.OpenRead("C:\\x.xml")) as List<Student>;  
  87.             foreach (Student s in stuList)  
  88.             {  
  89.                 MessageBox.Show(string.Format("{0} : {1} : {2} : {3}",  
  90.                     s.Name, s.Age, s.Class, s.Number));  
  91.             }  
  92.   
  93. 序列化Dirctionary  
  94.   
  95.     public struct DirectionList  
  96.     {  
  97.         [XmlAttribute("Name")]  
  98.         public string Name;  
  99.         [XmlElement("Value")]  
  100.         public int Value;  
  101.     }  
  102.   
  103. void Main(string[] args)  
  104.   
  105. {  
  106.   
  107.             Dictionary<string, int> list = new Dictionary<string, int>();  
  108.             list.Add("1", 100);  
  109.             list.Add("2", 200);  
  110.             list.Add("3", 300);  
  111.             list.Add("4", 400);  
  112.             list.Add("5", 500);  
  113.             list.Add("6", 600);  
  114.             list.Add("7", 700);  
  115.             list.Add("8", 800);  
  116.             list.Add("9", 900);  
  117.   
  118.             List<DirectionList> dirList = new List<DirectionList>();  
  119.             foreach (var s in list)  
  120.             {  
  121.                 dirList.Add(new DirectionList() { Name = s.Key, Value = s.Value });  
  122.             }  
  123.             XmlSerializer ser = new XmlSerializer(typeof(List<DirectionList>));  
  124.             ser.Serialize(File.Create("C:\\x.xml"), dirList);  
  125.   
  126. }  
  127.   
  128. 这里还要讲一点,在XmlSerializer中,不支持Dirctionary<>类型的对象,所以在序列化这种最常见类型的时候,只能按照它的格式先创建一个可以别序列化的类型,这里我定义了一个结构体,当然你也可以定义成其他的类。将Dictionary<>中的数据依次放进结构体以后就可以放入流中了。  
  129.   
  130. [XmlAttribute("Name")]意思是将这个字段作为xml的属性,属性名跟在“”中  
  131.   
  132. [XmlElement("Value")]意思是将这个字段做为xml的元素。  
  133.   
  134.   
  135. 反序列化Dirctionary  
  136.   
  137.   
  138.             XmlSerializer ser = new XmlSerializer(typeof(List<DirectionList>));  
  139.             List<DirectionList> dirList = ser.Deserialize(  
  140.                 File.OpenRead("C:\\x.xml")) as List<DirectionList>;  
  141.             foreach (var v in dirList)  
  142.             {  
  143.                 Console.WriteLine("{0} : {1}", v.Name, v.Value);  
  144.             }  
  145.   
  146. 其实我并不喜欢这个名称,感觉有点生化危机的feel,但是也就是这样了,没有太炫的地方,Deserialize反序列化。真希望.Net能集成Dirctionary<>对象,那我们这些懒人就方便了。  
  147.   
  148. 在需要序列化的队伍中,数组是很常见的类型,其次就是图片了  
  149.   
  150. 序列化图片  
  151.   
  152.     public struct ImageStruct  
  153.     {  
  154.         [XmlAttribute("Number")]  
  155.         public int number;  
  156.         [XmlElement("Image")]  
  157.         public byte[] picture;  
  158.     }  
  159.   
  160. void Main(string[] args)  
  161.   
  162. {  
  163.   
  164.             ImageStruct s = new ImageStruct() { number = 1picture = File.ReadAllBytes(@"11.jpg") };  
  165.             XmlSerializer ser = new XmlSerializer(typeof(ImageStruct));  
  166.             FileStream fs = File.Create("c:\\x.xml");  
  167.             ser.Serialize(fs, s);  
  168.             fs.Close();  
  169.   
  170. }  
  171.   
  172. 一样的,采用结构体来保存图片,这里我还加了个图片的名字,到时候查找起来也方便一些  
  173.   
  174. 图片反序列化  
  175.   
  176.             XmlSerializer ser = new XmlSerializer(typeof(ImageStruct));  
  177.             ImageStruct s = (ImageStruct)ser.Deserialize(File.OpenRead("c:\\x.xml"));  
  178.             pictureBox1.Image = Image.FromStream(new MemoryStream(s.picture));  
  179.   
  180. 没有花头的方式,利用memorystream来做缓存,这样会比较快一点,实际上我并没有怎么感觉。  
  181.   
  182. 图片数组序列化  
  183.   
  184.     public struct ImageStruct  
  185.     {  
  186.         [XmlAttribute("Number")]  
  187.         public int number;  
  188.         [XmlElement("Image")]  
  189.         public byte[] picture;  
  190.     }  
  191.   
  192. void Main(string[] args)  
  193.   
  194. {  
  195.   
  196.             List<ImageStruct> imageList = new List<ImageStruct>();  
  197.             imageList.Add(new ImageStruct()  
  198.             {  
  199.                 number = 1,  
  200.                 picture = File.ReadAllBytes(@"11.jpg")  
  201.             });  
  202.             imageList.Add(new ImageStruct()  
  203.             {  
  204.                 number = 2,  
  205.                 picture = File.ReadAllBytes(@"22.jpg")  
  206.             });  
  207.   
  208.             XmlSerializer ser = new XmlSerializer(typeof(List<ImageStruct>));  
  209.             FileStream fs = File.Create("c:\\x.xml");  
  210.             ser.Serialize(fs, imageList);  
  211.             fs.Close();  
  212.   
  213. }  
  214.   
  215. 图片数组反序列化  
  216.   
  217.             XmlSerializer ser = new XmlSerializer(typeof(List<ImageStruct>));  
  218.             List<ImageStruct> s = (List<ImageStruct>)ser.Deserialize(File.OpenRead("c:\\x.xml"));  
  219.             var im = from i in s  
  220.                      where i.number == 1  
  221.                      select i.picture;  
  222.   
  223.             //var im = s.Where(p => p.number == 1).Select(p => p.picture);  
  224.             foreach (var image in im)  
  225.             {  
  226.                 pictureBox1.Image = Image.FromStream(  
  227.                     new MemoryStream(image));  
  228.             }  
  229.   
  230. 这里还对数组结构进行了Linq查询,这样就可以很方便的查询图片了。  


 

[html] view plaincopy
  1. XML序列化与反序列化 整理文档XML序列化与反序列化 整理文档  
  2.   
  3. XML序列化与反序列化  
  4.     // OBJECT -> XML  
  5.     public static void SaveXml(string filePath, object obj) { SaveXml(filePath, obj, obj.GetType()); }  
  6.     public static void SaveXml(string filePath, object obj, System.Type type)  
  7.     {  
  8.         using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath))  
  9.         {  
  10.             System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(type);  
  11.             xs.Serialize(writer, obj);  
  12.             writer.Close();  
  13.         }  
  14.     }  
  15.     // XML -> OBJECT  
  16.     public static object LoadXml(string filePath, System.Type type)  
  17.     {  
  18.         if (!System.IO.File.Exists(filePath))  
  19.             return null;  
  20.         using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))  
  21.         {  
  22.             System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(type);  
  23.             object obj = xs.Deserialize(reader);  
  24.             reader.Close();  
  25.             return obj;  
  26.         }  
  27.     }  
  28.   
  29. 相关的常用Attribute(命名空间System.Xml.Serialization )  
  30.     [XmlRootAttribute("PurchaseOrder", Namespace="http://www.cpandl.com"IsNullable=false)]  // 指定根  
  31.     [XmlIgnoreAttribute]                                                                      // 跳过不序列化  
  32.     [XmlArrayAttribute("Items")] public OrderedItem[] OrderedItems;                           // 层次序列化: <Items><OrderedItem.../><OrderedItem.../>..</Items>  
  33.     [XmlElementAttribute(ElementName="Link"IsNullable=false)] public Link[] Links;          // 平面序列化: <Link ..../><Link .../>...  
  34.     [XmlAttribute("Cat")] public string Cat;                                                  // 表现为属性<... Cat=.. />  
  35.     [XmlElementAttribute(IsNullable=false)]                                                   // 表现为节点<Cat>..</cat>  
  36.   
  37. 相关的全部Attribute(命名空间System.Xml.Serialization )  
  38.     XmlAttributes                     表示一个特性对象的集合,这些对象控制 XmlSerializer 如何序列化和反序列化对象。   
  39.     XmlArrayAttribute                 指定 XmlSerializer 应将特定的类成员序列化为 XML 元素数组。   
  40.     XmlArrayItemAttribute             指定 XmlSerializer 可以放置在序列化数组中的派生类型。   
  41.     XmlArrayItemAttributes            表示 XmlArrayItemAttribute 对象的集合。   
  42.     XmlAttributeAttribute             指定 XmlSerializer 应将类成员作为 XML 特性序列化。   
  43.     XmlChoiceIdentifierAttribute      指定可以通过使用枚举来进一步消除成员的歧义。   
  44.     XmlElementAttribute               在 XmlSerializer 序列化或反序列化包含对象时,指示公共字段或属性表示 XML 元素。   
  45.     XmlElementAttributes              表示 XmlElementAttribute 的集合,XmlSerializer 将其用于它重写序列化类的默认方式。   
  46.     XmlEnumAttribute                  控制 XmlSerializer 如何序列化枚举成员。   
  47.     XmlIgnoreAttribute                指示 XmlSerializer 的 Serialize 方法不序列化公共字段或公共读/写属性值。   
  48.     XmlIncludeAttribute               允许 XmlSerializer 在它序列化或反序列化对象时识别类型。   
  49.     XmlRootAttribute                  控制视为 XML 根元素的属性目标的 XML 序列化。   
  50.     XmlTextAttribute                  当序列化或反序列化包含类时,向 XmlSerializer 指示应将此成员作为 XML 文本处理。   
  51.     XmlTypeAttribute                  控制当属性目标由 XmlSerializer 序列化时生成的 XML 架构。   
  52.     XmlAnyAttributeAttribute          指定成员(返回 XmlAttribute 对象的数组的字段)可以包含任何 XML 属性。   
  53.     XmlAnyElementAttribute            指定成员(返回 XmlElement 或 XmlNode 对象的数组的字段)可以包含对象,该对象表示在序列化或反序列化的对象中没有相应成员的所有 XML 元素。   
  54.     XmlAnyElementAttributes           表示 XmlAnyElementAttribute 对象的集合。   
  55.     XmlAttributeEventArgs             为 UnknownAttribute 事件提供数据。   
  56.     XmlAttributeOverrides             允许您在使用 XmlSerializer 序列化或反序列化对象时重写属性、字段和类特性。   
  57.     XmlElementEventArgs               为 UnknownElement 事件提供数据。   
  58.     XmlNamespaceDeclarationsAttribute 指定目标属性、参数、返回值或类成员包含与 XML 文档中所用命名空间关联的前缀。   
  59.     XmlNodeEventArgs                  为 UnknownNode 事件提供数据。   
  60.     XmlSerializer                     将对象序列化到 XML 文档中和从 XML 文档中反序列化对象。XmlSerializer 使您得以控制如何将对象编码到 XML 中。   
  61.     XmlSerializerNamespaces           包含 XmlSerializer 用于在 XML 文档实例中生成限定名的 XML 命名空间和前缀。   
  62.     XmlTypeMapping                    包含从一种类型到另一种类型的映射。   
  63.   
  64.   
  65. xml序列化答疑  
  66.     (1)需序列化的字段必须是公共的(public)  
  67.     (2)需要序列化的类都必须有一个无参的构造函数  
  68.     (3)枚举变量可序列化为字符串,无需用[XmlInclude]  
  69.     (4)导出非基本类型对象,都必须用[XmlInclude]事先声明。该规则递归作用到子元素  
  70.         如导出ArrayList对象,若其成员是自定义的,需预包含处理:  
  71.         using System.Xml.Serialization;  
  72.         [XmlInclude(typeof(自定义类))]  
  73.     (5)Attribute中的IsNullable参数若等于false,表示若元素为null则不显示该元素。  
  74.         也就是说:针对值类型(如结构体)该功能是实效的  
  75.         若数组包含了100个空间,填充了10个类对象,则序列化后只显示10个节点  
  76.         若数组包含了100个空间,填充了10个结构体对象,则序列化后会显示100个节点  
  77.     (6)真正无法XML序列化的情况  
  78.         某些类就是无法XML序列化的(即使使用了[XmlInclude])  
  79.             IDictionary(如HashTable)  
  80.             System.Drawing.Color  
  81.             System.Drawing.Font  
  82.             SecurityAttribute声明  
  83.         父类对象赋予子类对象值的情况  
  84.         对象间循环引用  
  85.     (7)对于无法XML序列化的对象,可考虑  
  86.         使用自定义xml序列化(实现IXmlSerializable接口)  
  87.         实现IDictionary的类,可考虑(1)用其它集合类替代;(2)用类封装之,并提供Add和this函数  
  88.         某些类型需要先经过转换,然后才能序列化为 XML。如XML序列化System.Drawing.Color,可先用ToArgb()将其转换为整数   
  89.         过于复杂的对象用xml序列化不便的话,可考虑用二进制序列化   
  90.   
  91.   
  92. ------------------------------------------------------------------------------------  
  93. 高级议题  
  94. ------------------------------------------------------------------------------------  
  95. 序列化中异常的扑捉  
  96.     使用Exception.Message只会得到简单的信息“行***错误"  
  97.     可以使用Exception.InnerException.Message得到更详尽的信息  
  98.   
  99. 可使用事件代理来处理解析不了的XML节点  
  100.     XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));  
  101.     serializer.UnknownNode+= new XmlNodeEventHandler(serializer_UnknownNode);  
  102.     serializer.UnknownAttribute+= new  XmlAttributeEventHandler(serializer_UnknownAttribute);  
  103.     protected void serializer_UnknownNode(object sender, XmlNodeEventArgs e)  
  104.     {  
  105.       Console.WriteLine("Unknown Node:" +   e.Name + "\t" + e.Text);  
  106.     }  
  107.     protected void serializer_UnknownAttribute(object sender, XmlAttributeEventArgs e)  
  108.     {  
  109.       System.Xml.XmlAttribute attr = e.Attr;  
  110.       Console.WriteLine("Unknown attribute " +  attr.Name + "='" + attr.Value + "'");  
  111.     }  
  112.   
  113. 集合类(IEnumerable, ICollection)必须满足下列规则才可XML序列化:  
  114.     - 不得实现 IDictionary。  
  115.     - 必须有一个 Add 方法,该方法不是由该接口定义的,因为它通常是为该集合将要容纳的专用类型而创建的  
  116.     - 必须有一个索引器, 且参数为 System.Int32 (C# int)  
  117.     - 在 Add、Count 和索引器中不能有任何安全特性(SecurityAttribute)  
  118.     可序列化集合类例程:  
  119.         public class PublisherCollection : CollectionBase  
  120.         {  
  121.           public int Add(Publisher value)  
  122.           {  
  123.             return base.InnerList.Add(value);  
  124.           }  
  125.           public Publisher this[int idx]  
  126.           {  
  127.             get { return (Publisher) base.InnerList[idx]; }  
  128.             set { base.InnerList[idx] = value; }  
  129.           }  
  130.         }   
  131.   
  132.   
  133. 某些类是以程序集的形式提供的,无法修改其源码。可用XmlAttributeOverrides设置其序列化特性  
  134.      XML目标  
  135.         <?xml version="1.0" encoding="utf-8"?>  
  136.         <Inventory xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
  137.            <Product>  
  138.               <ProductID>100</ProductID>  
  139.               <ProductName>Product Thing</ProductName>  
  140.               <SupplierID>10</SupplierID>  
  141.            </Product>  
  142.            <Book>  
  143.               <ProductID>101</ProductID>  
  144.               <ProductName>How to Use Your New Product Thing</ProductName>  
  145.               <SupplierID>10</SupplierID>  
  146.               <ISBN>123456789</ISBN>  
  147.            </Book>  
  148.         </Inventory>  
  149.     源类(无法修改)  
  150.         public class Inventory  
  151.         {  
  152.            private Product[] stuff;  
  153.            public Inventory() {}  
  154.            public Product[] InventoryItems {get {return stuff;} set {stuff=value;}}  
  155.         }  
  156.     附加XmlAttributeOverrides后即可序列化  
  157.        XmlAttributes attrs = new XmlAttributes();  
  158.        attrs.XmlElements.Add(new XmlElementAttribute("Book", typeof(BookProduct)));  
  159.        attrs.XmlElements.Add(new XmlElementAttribute("Product", typeof(Product)));  
  160.        //add to the Attributes collection  
  161.        XmlAttributeOverrides attrOver = new XmlAttributeOverrides();  
  162.        attrOver.Add(typeof(Inventory), "InventoryItems", attrs);  
  163.        //deserialize and load data into the listbox from deserialized object  
  164.        FileStream f=new FileStream("..\\..\\..\\inventory.xml",FileMode.Open);  
  165.        XmlSerializer newSr=new XmlSerializer(typeof(Inventory), attrOver);  
  166.        Inventory newInv = (Inventory)newSr.Deserialize(f);  
  167.   
  168.    
  169.   
  170.    
  171.   
  172. ------------------------------------------------------------------------------------  
  173. 最简单的示例  
  174. -------------------------------------------------------------------------------------  
  175. 类设计  
  176.     public class MyClass  {public MyObject MyObjectProperty;}  
  177.     public class MyObject {public string ObjectName;}  
  178.   
  179. 序列化的 XML:  
  180.     <MyClass>  
  181.         <MyObjectProperty>  
  182.             <Objectname>My String</ObjectName>  
  183.         </MyObjectProperty>  
  184.     </MyClass>  
  185.   
  186.   
  187.     
  188. ------------------------------------------------------------------------------------  
  189. 示例: 序列化数组,并限制数组元素类型  
  190. -------------------------------------------------------------------------------------  
  191. 类设计  
  192.     public class Things  
  193.     {  
  194.        [XmlElement(DataType = typeof(string)), XmlElement(DataType = typeof(int))]  
  195.        public object[] StringsAndInts;  
  196.     }  
  197.   
  198. 生成的 XML 可能为:  
  199.     <Things>  
  200.        <string>Hello</string>  
  201.        <int>999</int>  
  202.        <string>World</string>  
  203.     </Things>  
  204.   
  205.    
  206.   
  207. -------------------------------------------------------------------------------------  
  208. 示例: 序列化数组  
  209. -------------------------------------------------------------------------------------  
  210. 类设计  
  211.     using System.Xml.Serialization;  
  212.     [XmlRootAttribute("LinkLibrary", IsNullable = falseNamespace="http://www.wztelecom.cn")]  
  213.     public class LinkLib  
  214.     {  
  215.         [XmlElementAttribute(ElementName="Link"IsNullable=false)]  
  216.         public Link[] Links;  
  217.         public LinkLib()  
  218.         {  
  219.             Links = new Link[50];  
  220.             Links[0] = new Link("aa", "aa", "aa");  
  221.             Links[1] = new Link("bb", "aa", "aa");  
  222.             Links[2] = new Link("cc", "aa", "aa");  
  223.             Links[3] = new Link("aa", "aa", "aa");  
  224.             Links[4] = new Link("aa", "aa", "aa");  
  225.             Links[5] = new Link("aa", "aa", "aa");  
  226.             Links[6] = new Link("aa", "aa", "aa");  
  227.             Links[7] = new Link("aa", "aa", "aa");  
  228.             Links[8] = new Link("aa", "aa", "aa");  
  229.             Links[9] = new Link("aa", "aa", "aa");  
  230.         }  
  231.     }  
  232.     public class Link  
  233.     {  
  234.         [XmlAttribute("Cat")] public string Cat;  
  235.         [XmlAttribute("Url")] public string Url;  
  236.         [XmlAttribute("Desc")]public string Desc;  
  237.         public Link(){}  
  238.         public Link(string cat, string url, string desc)  
  239.         {  
  240.             Cat = cat;  
  241.             Url = url;  
  242.             Desc = desc;  
  243.         }  
  244.     }  
  245.   
  246. 目标XML文件  
  247.     <?xml version="1.0" encoding="utf-8"?>  
  248.     <LinkLibrary xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
  249.       <Link Cat="aa" Url="aa" Desc="aa" />  
  250.       <Link Cat="bb" Url="aa" Desc="aa" />  
  251.       <Link Cat="cc" Url="aa" Desc="aa" />  
  252.       <Link Cat="aa" Url="aa" Desc="aa" />  
  253.       <Link Cat="aa" Url="aa" Desc="aa" />  
  254.       <Link Cat="aa" Url="aa" Desc="aa" />  
  255.       <Link Cat="aa" Url="aa" Desc="aa" />  
  256.       <Link Cat="aa" Url="aa" Desc="aa" />  
  257.       <Link Cat="aa" Url="aa" Desc="aa" />  
  258.       <Link Cat="aa" Url="aa" Desc="aa" />  
  259.     </LinkLibrary>  
  260.   
  261. 若使用[XmlArrayAttribute("Links")] public Link[] Links;则序列化后的xml文件会多出一层:  
  262.     <?xml version="1.0" encoding="utf-8"?>  
  263.     <LinkLibrary xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
  264.          <Links>  
  265.               <Link Cat="aa" Url="aa" Desc="aa" />  
  266.               <Link Cat="bb" Url="aa" Desc="aa" />  
  267.               <Link Cat="cc" Url="aa" Desc="aa" />  
  268.               <Link Cat="aa" Url="aa" Desc="aa" />  
  269.               <Link Cat="aa" Url="aa" Desc="aa" />  
  270.               <Link Cat="aa" Url="aa" Desc="aa" />  
  271.               <Link Cat="aa" Url="aa" Desc="aa" />  
  272.               <Link Cat="aa" Url="aa" Desc="aa" />  
  273.               <Link Cat="aa" Url="aa" Desc="aa" />  
  274.               <Link Cat="aa" Url="aa" Desc="aa" />  
  275.          </Links>  
  276.     </LinkLibrary>  
  277.   
  278.    
  279.   
  280. -------------------------------------------------------------------------------------  
  281. 示例:使用自定义序列化序列化Dictionary对象  
  282. -------------------------------------------------------------------------------------  
  283. XML目标  
  284.     <?xml version="1.0" encoding="utf-8"?>  
  285.     <FactTableDef>  
  286.       <Name>FactTableDef1</Name>  
  287.       <Owner>owner1</Owner>  
  288.       <SourceTable>sourceTable1</SourceTable>  
  289.       <ColumnMeasureMaps>  
  290.         <Map Column="column1" Measure="Measure1" />  
  291.         <Map Column="column2" Measure="Measure2" />  
  292.         <Map Column="column3" Measure="Measure3" />  
  293.       </ColumnMeasureMaps>  
  294.       <ColumnDimensionMaps>  
  295.         <Map Column="column4" Dimension="Dimension4" />  
  296.         <Map Column="column5" Dimension="Dimension5" />  
  297.         <Map Column="column6" Dimension="Dimension6" />  
  298.       </ColumnDimensionMaps>  
  299.     </FactTableDef>  
  300.   
  301. 类源码  
  302.     using System;  
  303.     using System.Collections.Generic;  
  304.     using System.Text;  
  305.     using System.Runtime.Serialization;  
  306.     using System.Xml;  
  307.     using System.Xml.Serialization;  
  308.   
  309.     namespace WZDM.OLAP  
  310.     {  
  311.         [System.Serializable()]  
  312.         [XmlInclude(typeof(FactTableDef))]  
  313.         public class FactTableDef : System.Xml.Serialization.IXmlSerializable  
  314.         {  
  315.             public string Name;               // 名称  
  316.             public string Owner;              // 事实表属主  
  317.             public string SourceTable;        // 源表  
  318.             public Dictionary<string, string> ColumnMeasureMaps;   // 字段和量度对应关系  
  319.             public Dictionary<string, string> ColumnDimensionMaps; // 字段和维度对应关系  
  320.       
  321.       
  322.             public FactTableDef() { }  
  323.             ...  
  324.       
  325.             public void WriteXml(System.Xml.XmlWriter writer)  
  326.             {  
  327.                 writer.WriteElementString("Name", this.Name);  
  328.                 writer.WriteElementString("Owner", this.Owner);  
  329.                 writer.WriteElementString("SourceTable", this.SourceTable);  
  330.       
  331.                 // ColumnMeasureMaps  
  332.                 writer.WriteStartElement("ColumnMeasureMaps");  
  333.                 foreach (string key in this.ColumnMeasureMaps.Keys)  
  334.                 {  
  335.                     writer.WriteStartElement("Map");  
  336.                     writer.WriteAttributeString("Column", key);  
  337.                     writer.WriteAttributeString("Measure", ColumnMeasureMaps[key]);  
  338.                     writer.WriteEndElement();  
  339.                 }  
  340.                 writer.WriteEndElement();  
  341.       
  342.       
  343.                 // ColumnDimensionMaps  
  344.                 writer.WriteStartElement("ColumnDimensionMaps");  
  345.                 foreach (string key in this.ColumnDimensionMaps.Keys)  
  346.                 {  
  347.                     writer.WriteStartElement("Map");  
  348.                     writer.WriteAttributeString("Column", key);  
  349.                     writer.WriteAttributeString("Dimension", ColumnDimensionMaps[key]);  
  350.                     writer.WriteEndElement();  
  351.                 }  
  352.                 writer.WriteEndElement();  
  353.             }  
  354.       
  355.       
  356.             public void  ReadXml(System.Xml.XmlReader reader)  
  357.             {  
  358.                 reader.Read();  
  359.                 this.Name = reader.ReadElementString("Name");  
  360.                 this.Owner = reader.ReadElementString("Owner");  
  361.                 this.SourceTable = reader.ReadElementString("SourceTable");  
  362.       
  363.                 // ColumnMeasureMaps  
  364.                 ColumnMeasureMaps = new Dictionary<string, string>();  
  365.                 reader.ReadStartElement("ColumnMeasureMaps");  
  366.                 reader.ReadToDescendant("Map");  
  367.                 do   
  368.                 {  
  369.                     string key = reader.GetAttribute("Column");  
  370.                     string item = reader.GetAttribute("Measure");  
  371.                     ColumnMeasureMaps.Add(key, item);  
  372.                 }while (reader.ReadToNextSibling("Map"));  
  373.                 reader.ReadEndElement();  
  374.       
  375.                 // ColumnDimensionMaps  
  376.                 ColumnDimensionMaps = new Dictionary<string, string>();  
  377.                 reader.ReadStartElement("ColumnDimensionMaps");  
  378.                 reader.ReadToDescendant("Map");  
  379.                 do  
  380.                 {  
  381.                     string key = reader.GetAttribute("Column");  
  382.                     string item = reader.GetAttribute("Dimension");  
  383.                     ColumnDimensionMaps.Add(key, item);  
  384.                 } while (reader.ReadToNextSibling("Map"));  
  385.                 reader.ReadEndElement();  
  386.             }  
  387.         }  
  388.     }   
0 0