`
love19820823
  • 浏览: 974585 次
文章分类
社区版块
存档分类
最新评论

在.net 当中如何XML序列化一个Collection(转载)

 
阅读更多

在.net 当中如何XML序列化一个Collection

Collection主要是指像Array, ArrayList, List, Dictionary, HashTable这些数据类型,大家平时用的很多。如果一个类中有一个Collection类型的成员,在对这个类进行XML序列化的时候,应该如何处 理?应该说在.net当中这是比较简单的,只要建立一个XmlSerializer类就可以帮你自动搞定,不过有的时候你可能需要对自动的序列化过程施加 更多的控制,比如XML的结构是实现固定的,你必须按照要求去生成XML结构。

使用不同的属性 可以灵活的控制生成的XML,这里我就不多介绍了,主要讲一下如何序列化比较复杂的Collection结 构。下面的方法,对于所有实现了IEnumerable接口的Collection都有效。

我使用MSDN中的例子,不过没有使用数组或 者ArrayList,而是使用了比较高级的数据类型List<T>,希望在讲解如何序列化XML的同时给使用List<T>的 同学提供点参考。

序列化一个List<T>

下面的代码示范了如何序列化一个 List<T>,实际上和序列化其它类一样,把这个类扔给Serialize()函数即可。

using
 System;
using
 System.Collections.Generic;
using
 System.Linq;
using
 System.Text;
using
 System.Xml.Serialization;
using
 System.IO;

namespace
 SerializeCollection
{
    class
 Program
    {
        static
 void
 Main(string
[] args)
        {
            Program test = new
 Program();
            test.SerializeDocument("e://books.xml"
);
        }

        public
 void
 SerializeDocument(string
 filename)
        {
            // Creates a new XmlSerializer.
            XmlSerializer s =
            new
 XmlSerializer(typeof
(MyRootClass));

            // Writing the file requires a StreamWriter.
            TextWriter myWriter = new
 StreamWriter(filename);

            // Creates an instance of the class to serialize. 
            MyRootClass myRootClass = new
 MyRootClass();
            
            //create items
            Item item1 = new
 Item();
            // Sets the objects' properties.
            item1.ItemName = "Widget1"
;
            item1.ItemCode = "w1"
;
            item1.ItemPrice = 231;
            item1.ItemQuantity = 3;

            
            Item item2 = new
 Item();
            // Sets the objects' properties.
            item2.ItemName = "Widget2"
;
            item2.ItemCode = "w2"
;
            item2.ItemPrice = 800;
            item2.ItemQuantity = 2;

            // Sets the class's Items property to the list.
            myRootClass.Items.Add(item1);
            myRootClass.Items.Add(item2);

            /* Serializes the class, writes it to disk, and closes 
               the TextWriter. */
            s.Serialize(myWriter, myRootClass);
            myWriter.Close();
        }

    }

    // This is the class that will be serialized.
    [Serializable]
    public
 class
 MyRootClass
    {
        public
 MyRootClass()
        {
            items = new
 List<Item>();
        }

        private
 List<Item> items;

        public
 List<Item> Items
        {
            get { return
 items; }
            set { items = value
; }
        }
    }

    public
 class
 Item
    {
        [XmlElement(ElementName = "OrderItem"
)]
        public
 string
 ItemName;
        public
 string
 ItemCode;
        public
 decimal
 ItemPrice;
        public
 int
 ItemQuantity;
    }


}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

最后序列化成的XML:

<?
xml
 version
="1.0"
 encoding
="utf-8"
?>
<
MyRootClass
 xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:xsd
="http://www.w3.org/2001/XMLSchema"
>
  <
Items
>
    <
Item
>
      <
OrderItem
>
Widget1</
OrderItem
>
      <
ItemCode
>
w1</
ItemCode
>
      <
ItemPrice
>
231</
ItemPrice
>
      <
ItemQuantity
>
3</
ItemQuantity
>
    </
Item
>
    <
Item
>
      <
OrderItem
>
Widget2</
OrderItem
>
      <
ItemCode
>
w2</
ItemCode
>
      <
ItemPrice
>
800</
ItemPrice
>
      <
ItemQuantity
>
2</
ItemQuantity
>
    </
Item
>
  </
Items
>
</
MyRootClass
>
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

如果这个List<T>中的成员的类还有继承关系

现在把情况变得复杂一点,因为多态,List<T>中的类可能是指定类型的子类型,这个时候会出现什么情况呢?

我们增加一个BookItem类,继承自Item 类。

using
 System;
using
 System.Collections.Generic;
using
 System.Linq;
using
 System.Text;
using
 System.Xml.Serialization;
using
 System.IO;

namespace
 SerializeCollection
{
    class
 Program
    {
        static
 void
 Main(string
[] args)
        {
            Program test = new
 Program();
            test.SerializeDocument("e://books.xml"
);
        }

        public
 void
 SerializeDocument(string
 filename)
        {
            // Creates a new XmlSerializer.
            XmlSerializer s =
            new
 XmlSerializer(typeof
(MyRootClass));

            // Writing the file requires a StreamWriter.
            TextWriter myWriter = new
 StreamWriter(filename);

            // Creates an instance of the class to serialize. 
            MyRootClass myRootClass = new
 MyRootClass();

            /* Uses a more advanced method of creating an list:
         create instances of the Item and BookItem, where BookItem 
         is derived from Item. */
            Item item1 = new
 Item();
            // Sets the objects' properties.
            item1.ItemName = "Widget1"
;
            item1.ItemCode = "w1"
;
            item1.ItemPrice = 231;
            item1.ItemQuantity = 3;

            BookItem bookItem = new
 BookItem();
            // Sets the objects' properties.
            bookItem.ItemCode = "w2"
;
            bookItem.ItemPrice = 123;
            bookItem.ItemQuantity = 7;
            bookItem.ISBN = "34982333"
;
            bookItem.Title = "Book of Widgets"
;
            bookItem.Author = "John Smith"
;

            // Sets the class's Items property to the list.
            myRootClass.Items.Add(item1);
            myRootClass.Items.Add(bookItem);

            /* Serializes the class, writes it to disk, and closes 
               the TextWriter. */
            s.Serialize(myWriter, myRootClass);
            myWriter.Close();
        }

    }

    // This is the class that will be serialized.
    [Serializable]
    public
 class
 MyRootClass
    {
        public
 MyRootClass()
        {
            items = new
 List<Item>();
        }

        private
 List<Item> items;

        public
 List<Item> Items
        {
            get { return
 items; }
            set { items = value
; }
        }
    }

    public
 class
 Item
    {
        [XmlElement(ElementName = "OrderItem"
)]
        public
 string
 ItemName;
        public
 string
 ItemCode;
        public
 decimal
 ItemPrice;
        public
 int
 ItemQuantity;
    }

    public
 class
 BookItem : Item
    {
        public
 string
 Title;
        public
 string
 Author;
        public
 string
 ISBN;
    }



}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

修改代码后,我们再运行,出现如下错误“不应是类型 SerializeCollection.BookItem。使用 XmlInclude 或 SoapInclude 属性静态指定非已知的类型”,看来是系统在做序列化的时候,搞不清楚List中的成员到底是什么类型。这个时候就要使用XmlArrayItem 来 帮忙了。MyRootClass类的Item成员前加入XmlArrayItem标志。

[XmlArrayItem(ElementName= "Item"
, 
   IsNullable=true
,
   Type = typeof
(Item),
   Namespace = "http://www.aboutdnn.com"
),
   XmlArrayItem(ElementName = "BookItem"
, 
   IsNullable = true
, 
   Type = typeof
(BookItem),
   Namespace = http://www.aboutdnn.com

)]
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

修改后的代码如下:

using
 System;
using
 System.Collections.Generic;
using
 System.Linq;
using
 System.Text;
using
 System.Xml.Serialization;
using
 System.IO;

namespace
 SerializeCollection
{
    class
 Program
    {
        static
 void
 Main(string
[] args)
        {
            Program test = new
 Program();
            test.SerializeDocument("e://books.xml"
);
        }

        public
 void
 SerializeDocument(string
 filename)
        {
            // Creates a new XmlSerializer.
            XmlSerializer s =
            new
 XmlSerializer(typeof
(MyRootClass));

            // Writing the file requires a StreamWriter.
            TextWriter myWriter = new
 StreamWriter(filename);

            // Creates an instance of the class to serialize. 
            MyRootClass myRootClass = new
 MyRootClass();

            /* Uses a more advanced method of creating an list:
         create instances of the Item and BookItem, where BookItem 
         is derived from Item. */
            Item item1 = new
 Item();
            // Sets the objects' properties.
            item1.ItemName = "Widget1"
;
            item1.ItemCode = "w1"
;
            item1.ItemPrice = 231;
            item1.ItemQuantity = 3;

            BookItem bookItem = new
 BookItem();
            // Sets the objects' properties.
            bookItem.ItemCode = "w2"
;
            bookItem.ItemPrice = 123;
            bookItem.ItemQuantity = 7;
            bookItem.ISBN = "34982333"
;
            bookItem.Title = "Book of Widgets"
;
            bookItem.Author = "John Smith"
;

            // Sets the class's Items property to the list.
            myRootClass.Items.Add(item1);
            myRootClass.Items.Add(bookItem);

            /* Serializes the class, writes it to disk, and closes 
               the TextWriter. */
            s.Serialize(myWriter, myRootClass);
            myWriter.Close();
        }

    }

    // This is the class that will be serialized.
    [Serializable]
    public
 class
 MyRootClass
    {
        public
 MyRootClass()
        {
            items = new
 List<Item>();
        }

        private
 List<Item> items;

        [XmlArrayItem(ElementName = "Item"
,
   IsNullable = true
,
   Type = typeof
(Item),
   Namespace = "http://www.aboutdnn.com"
),
   XmlArrayItem(ElementName = "BookItem"
,
   IsNullable = true
,
   Type = typeof
(BookItem),
   Namespace = "http://www.aboutdnn.com"
)]

        public
 List<Item> Items
        {
            get { return
 items; }
            set { items = value
; }
        }
    }

    public
 class
 Item
    {
        [XmlElement(ElementName = "OrderItem"
)]
        public
 string
 ItemName;
        public
 string
 ItemCode;
        public
 decimal
 ItemPrice;
        public
 int
 ItemQuantity;
    }

    public
 class
 BookItem : Item
    {
        public
 string
 Title;
        public
 string
 Author;
        public
 string
 ISBN;
    }



}

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

序列化后的XML如下:

<?
xml
 version
="1.0"
 encoding
="utf-8"
?>

< MyRootClass xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd ="http://www.w3.org/2001/XMLSchema" >
< Items >
< Item xmlns ="http://www.aboutdnn.com" >
< OrderItem > Widget1</ OrderItem >
< ItemCode > w1</ ItemCode >
< ItemPrice > 231</ ItemPrice >
< ItemQuantity > 3</ ItemQuantity >
</ Item >
< BookItem xmlns ="http://www.aboutdnn.com" >
< ItemCode > w2</ ItemCode >
< ItemPrice > 123</ ItemPrice >
< ItemQuantity > 7</ ItemQuantity >
< Title > Book of Widgets</ Title >
< Author > John Smith</ Author >
< ISBN > 34982333</ ISBN >
</ BookItem >
</ Items >
</ MyRootClass >
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

可以看到,已经根据不同的数据类型,序列化为不同名字的节点。这个时候,如果你还想修改XML中<Items>节点的名字或者添加属 性,XmlArrayAttribute 可 以帮你的忙,这个你可以自己试试。

分享到:
评论

相关推荐

    .NET面试题A(问题与答案)

    5. 线程同步:在.NET中,对象的方法默认是线程不安全的,一次只有一个线程可以访问某个对象的方法。 6. 位运算:`2 表示二进制左移3位,相当于2乘以2的3次方,结果为8。 7. 内存操作:C#支持 unsafe 模式下的指针...

    ADO.NET高级编程

    数据集可以被序列化为XML格式,这不仅便于数据的交换和持久化,也使得ADO.NET能够无缝地与其他支持XML的应用或服务集成。例如,通过将DataSet转换为XML,可以轻松实现数据的远程传输或导入导出功能。 ### 事务处理 ...

    进入IT企业必读的200个+.NET面试题.pdf )

    - .NET提供了多种序列化机制,包括二进制序列化、XML序列化、JSON序列化等。 通过以上章节的详细解析,读者可以全面地了解.NET框架的基础知识和技术要点,这对于准备进入IT行业的技术人员来说是非常宝贵的资源。

    VB.Net高级编程

    9. **XML和JSON处理**:VB.Net提供了内置的XML和JSON支持,包括XML文档对象模型(DOM)、XML序列化和反序列化,以及JSON.NET库,方便数据交换和存储。 10. **.NET Framework和.NET Core**:VB.Net是.NET平台的一...

    基于C#的 .NET Framework程序设计ppt

    【Microsoft .NET Framework概述】:.NET Framework是微软推出的一个全面的开发平台,它包含了运行托管代码所需的所有组件,如公共语言运行时(CLR)、类库以及开发工具。该框架提供了一个安全、高效的环境,使得...

    可序列化的ObservableCollection替代

    标题中的“可序列化的ObservableCollection替代”指的是在.NET框架中,开发者经常使用的`ObservableCollection&lt;T&gt;`类的一个增强版本,这个版本增加了序列化能力。`ObservableCollection&lt;T&gt;`是.NET Framework提供的一...

    C# xmlToList xml转换成对象

    通常,这涉及到反序列化XML节点的属性或子元素到T类型的对象的属性。 总的来说,C#提供了多种方式来处理XML数据,无论是简单的还是复杂的XML结构,都能找到合适的解决方案。这两种方法分别展示了使用传统XML API和...

    asp.net面试题

    - 支持二进制序列化和XML序列化。 - 可以自定义序列化过程。 #### 33. .Net中的垃圾回收机制 - **知识点**: - GC(Garbage Collection):自动管理内存,回收不再使用的对象。 - 特点: - 自动触发。 - 无需...

    .net内存宝典 这本书是学习.net开发的必修, 比clr via c#要强哦

    这可能包括XML、JSON和二进制序列化方式的比较。 9. **.NET框架新特性**:随着.NET框架的不断发展,新的内存管理特性和优化也在不断出现。书中的最新版可能涉及.NET Core和.NET 5及以上版本的内存管理改进。 总之...

    XML文件操作实用指南.doc

    总的来说,XML文件操作涉及到解析、验证、操作和序列化等多个环节,.NET框架为此提供了丰富的类库支持。理解DOM和相关类的工作原理,是高效处理XML文档的基础。在实际应用中,开发者可以根据需求选择合适的API,实现...

    探讨:使用XMLSerialize 序列化与反序列化

    在.NET框架中,序列化通常可以使用System.Xml.Serialization命名空间下的XmlSerializer类来完成。XmlSerializer类能够将符合Serializable属性的对象,转换为XML格式的数据。在反序列化过程中,它可以将XML数据转换回...

    C#,.Net软件工程师面试题

    ### C# 和 .Net 软件工程师面试知识点解析 #### 1. 类与结构的区别 - **定义**: - **类**:是引用类型,使用 `class` ... - 常见的序列化形式包括 XML、JSON 等。 - 反序列化则是将这些数据形式还原成对象的过程。

    ASP.NET面试题3

    - 在.NET中,可以使用`[Serializable]`属性标记类,使其支持序列化功能。 3. **垃圾回收(Garbage Collection, GC):** - 垃圾回收是.NET运行时自动管理内存的一项关键技术。 - 它负责自动释放不再使用的对象所...

    .NET程序员[整理].pdf

    11. .NET的序列化和远程处理:文档中可能包含有关数据序列化和.NET Remoting的内容,这对于分布式应用程序开发至关重要。 12. .NET的Web服务和API:内容提到了***、Web Services、Web API、SOAP、XML和JSON等Web...

    .net Framwork 复习试题与笔记

    - **XML序列化**:可读性强,适用于文档交换。 #### 二十、委托与协变逆变 - **委托**:一种引用类型,用于封装方法的引用。 - **协变**:允许泛型类型接受派生类的实例。 - **逆变**:允许泛型类型接受基类的实例...

    .net笔试资料汇总下载

    11. **XML与JSON**:掌握XML的解析、创建、序列化,以及JSON的处理,如Newtonsoft.Json库的使用。 12. **单元测试与持续集成**:理解 NUnit、xUnit 等测试框架,以及TDD(Test-Driven Development)理念,了解...

    .Net经典面试33条题及答案

    18. **序列化**:序列化是将对象的状态转换为可存储或可传输的形式,如XML、JSON或二进制。反序列化则相反,将序列化的数据恢复为对象。 以上是.NET面试中常见的一些知识点,涵盖类与结构的区别、多线程、异常处理...

    33条C#、.Net经典面试题目及答案

    - 序列化是将对象的状态转换为可存储或传输的形式的过程,例如XML或二进制。 - 反序列化是将序列化的数据恢复为对象的过程,常用于持久化对象或跨网络传输。 这些知识点涵盖了C#和.NET的基础语法、并发控制、内存...

    C#及.Net经典面试题目及答案

    ### C#及.Net经典面试题目解析 #### 1\. .NET中类和结构的区别 - **定义**: 结构和类都是.NET中定义数据类型的手段,它们具有类似的语法,但结构....NET Framework提供了多种序列化技术,如二进制序列化和XML序列化。

    NET面试题库,含答案

    15. Collection 和 Collections 的区别:Collection 是集合类的上级接口,Collections 是针对集合类的一个帮助类,它提供一系列静态方法来实现对各种集合的搜索、排序、线程安全化操作。 16. C# 中委托是什么?事件...

Global site tag (gtag.js) - Google Analytics