在.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;
}
}
最后序列化成的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>
如果这个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;
}
}
修改代码后,我们再运行,出现如下错误“不应是类型 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)]
修改后的代码如下:
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;
}
}
序列化后的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>
可以看到,已经根据不同的数据类型,序列化为不同名字的节点。这个时候,如果你还想修改XML中<Items>节点的名字或者添加属性,XmlArrayAttribute可以帮你的忙,这个你可以自己试试。
参考文档:
XmlArrayAttribute Class:http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayattribute.aspx
对于所有控制XML序列化的Attributes,请参考这里:Attributes That Control XML Serialization
转载于:https://www.cnblogs.com/DotNetNuke/archive/2010/03/07/1680267.html
在.net 当中如何XML序列化一个Collection相关推荐
- 利用.NET的XML序列化解决系统配置问题
作者:未知 请作者速与本人联系 出自: http://blog.csdn.net/ycl111/ 在Web系统开发中,我们经常需要读取和设置一些系统配置项,常见的例如数据库连接字符串.上传路径等等 ...
- c语言xml序列化,C# XML和实体类之间相互转换(序列化和反序列化)
我们需要在XML与实体类,DataTable,List之间进行转换,下面是XmlUtil类,该类来自网络并稍加修改. using System; using System.Collections.Ge ...
- XML序列化以及新增节点XMLHelper
介绍利用XMLHelper类实现XML的新建以及反序列化类的操作,XMLHelper见最底部 1.XML新增 document = XmlHelper.CreateXmlDocument(" ...
- Java对象XML序列化框架-Simple2.0
Java对象XML序列化框架-Simple2.0 Simple是一个XML序列化框架,一个Java 版本宽容的序列化框架,能够快速在Java 平台上开发XML.支持通过annotations完全配置化 ...
- XML序列化和反序列化(C#)
主要参考资料: http://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part-1 http ...
- 开心网外挂开发之 XML序列化于反序列化
通过昨天的文章我们已经了解了开发一个开心网的外挂所需要的最基本的东本,接下来的工作可以说基本上就上围绕这个基础来进行的,我写这一系列文章主要的目地不仅仅是为了让大家了解怎么开发开心网外挂,最主要的目过 ...
- XML 序列化 【译】
原文连接:http://www.diranieh.com/NETSerialization/XMLSerialization.htm 总结: 介绍 XML 序列化示例 XML Schema 定义文档 ...
- 【.Net基础02】XML序列化问题
[背景描述]:在开发软件的过程中,经常需要通过XML序列化一些对象,用于数据的传输与存储 [问题描述]:现在有这样一个问题,有3三个类,Movie,Cinema,SuperCinema.SuperCi ...
- C#对象XML序列化(一):序列化方法和常用特性
.Net Framework提供了对应的System.Xml.Seriazliation.XmlSerializer负责把对象序列化到XML,和从XML中反序列化为对象.Serializer的使用比较 ...
最新文章
- 查看mysql日志文件大小和数据库大小
- 微信小程序左到右联动
- 面试题24. 反转链表
- java的io流的file类_java IO流 (一) File类的使用
- POJ-2480 Longge's problem 欧拉函数
- 【读书笔记】金字塔原理-目录
- axure插件安装360浏览器
- 七月算法-P2 概率论与数理统计(1)
- 智能仓储系统作业流程及价值
- 1区SCI潜力刊,中科院分区即将更新,有望冲击2区
- npm安装 elementui 报错:404 Not Found - GET https://registry.npmjs.org/@vue%2fvue-loader-v15 - Not found
- Android---universal-image-loader应用
- 【java笔记】字符流,Properties,序列化,打印流
- 【重磅新闻】罗永浩约战王自如:一场两败俱伤的战役!
- 请确保dx环境安装正常后进行开播_dx环境搭建
- hihoCoder #1902 字符替换
- 海康威视WEB3.0控件开发包提供的demo 调试
- 如何恢复断电造成的丢失文件
- 边缘计算网关助力建筑能耗监测系统
- 信息系统项目管理师备考经验分享