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

在.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学习笔记及其他代码应用

    43.try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后? 答:会执行,在return前执行。 44.两个对象值相同(x.equals(y) == true),但却可有不同...

    JAVA_API1.6文档(中文)

    java.sql 提供使用 JavaTM 编程语言访问并处理存储在数据源(通常是一个关系数据库)中的数据的 API。 java.text 提供以与自然语言无关的方式来处理文本、日期、数字和消息的类和接口。 java.text.spi java.text ...

    NHibernate中文帮助手册API

    第一个持久化类  1.3. 映射cat  1.4. 与Cat同乐  1.5. 总结  2. 体系结构(Architecture)  2.1. 概况(Overview)  2.2. 实例状态  2.3. 上下文相关的(Contextual)Session  3. 配置  3.1. 可编程...

    java api最新7.0

    java.sql 提供使用 JavaTM 编程语言访问并处理存储在数据源(通常是一个关系数据库)中的数据的 API。 java.text 提供以与自然语言无关的方式来处理文本、日期、数字和消息的类和接口。 java.text.spi java.text ...

    JavaAPI1.6中文chm文档 part1

    java.sql 提供使用 JavaTM 编程语言访问并处理存储在数据源(通常是一个关系数据库)中的数据的 API。 java.text 提供以与自然语言无关的方式来处理文本、日期、数字和消息的类和接口。 java.text.spi java.text ...

    JavaAPI中文chm文档 part2

    java.sql 提供使用 JavaTM 编程语言访问并处理存储在数据源(通常是一个关系数据库)中的数据的 API。 java.text 提供以与自然语言无关的方式来处理文本、日期、数字和消息的类和接口。 java.text.spi java.text ...

    [Java参考文档]

    java.sql 提供使用 JavaTM 编程语言访问并处理存储在数据源(通常是一个关系数据库)中的数据的 API。 java.text 提供以与自然语言无关的方式来处理文本、日期、数字和消息的类和接口。 java.text.spi java.text ...

    [Java参考文档].JDK_API 1.6

    java.sql 提供使用 JavaTM 编程语言访问并处理存储在数据源(通常是一个关系数据库)中的数据的 API。 java.text 提供以与自然语言无关的方式来处理文本、日期、数字和消息的类和接口。 java.text.spi java.text ...

    Java 1.6 API 中文 New

    java.sql 提供使用 JavaTM 编程语言访问并处理存储在数据源(通常是一个关系数据库)中的数据的 API。 java.text 提供以与自然语言无关的方式来处理文本、日期、数字和消息的类和接口。 java.text.spi java.text ...

    JDK_1_6 API

    java.sql 提供使用 JavaTM 编程语言访问并处理存储在数据源(通常是一个关系数据库)中的数据的 API。 java.text 提供以与自然语言无关的方式来处理文本、日期、数字和消息的类和接口。 java.text.spi java.text ...

    超级有影响力霸气的Java面试题大全文档

    当客户机第一次调用一个Stateful Session Bean 时,容器必须立即在服务器中创建一个新的Bean实例,并关联到客户机上,以后此客户机调用Stateful Session Bean 的方法时容器会把调用分派到与此客户机相关联的Bean实例...

    Java SE实践教程 pdf格式电子书 下载(一) 更新

    9.1.4 对象XML序列化 227 9.2 练习 228 9.2.1 我的联系手册(JPA实现) 228 9.2.2 我的联系手册(JAXB实现) 238 9.3 小结 242 第10章 准备环球旅行——应用程序国际化 243 10.1 讲解 244 10.1.1 概念介绍 ...

    Java SE实践教程 pdf格式电子书 下载(四) 更新

    9.1.4 对象XML序列化 227 9.2 练习 228 9.2.1 我的联系手册(JPA实现) 228 9.2.2 我的联系手册(JAXB实现) 238 9.3 小结 242 第10章 准备环球旅行——应用程序国际化 243 10.1 讲解 244 10.1.1 概念介绍 ...

    java 面试题 总结

    在实现中,assertion就是在程序中的一条语句,它对一个boolean表达式进行检查,一个正确程序必须保证这个boolean表达式的值为true;如果该值为false,说明程序已经处于不正确的状态下,系统将给出警告或退出。...

Global site tag (gtag.js) - Google Analytics