最新推荐:
 
您的位置: IT频道>程序开发>微软开发区> 文章内容

随机推荐

Xml 串行话对象与反串行实例
[ 来源:博客网 ] [ 作者: ][ 时间:2007-10-30 ]   字体:[ ]
一个简单的例子,但是很实用。将对象直接串行话为xml文件,并可以反串行话为对象。
方法:


1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.IO;
5using System.Xml;
6using System.Xml.Serialization;
7using System.Collections.ObjectModel;
8
9namespace XmlBuilder
10{
11 /**////
12 ///
13 ///

14 public static class Localization
15 {
16 公有方法#region 公有方法
17 /**////
18 /// 序列化对象
19 ///

20 /// 文件信息名称

大泗县网,www.DaSiXian.com


21 /// 待序列化对象 大泗县网,www.DaSiXian.com
22 public static void SerializeObject(string fileName, object obj)
23 {
24 Stream writer = null;
25 try
26 {
27 Type type = obj.GetType();
28 XmlSerializer serializer = new XmlSerializer(type);
29
30 writer = new FileStream(fileName, FileMode.Create);
31 serializer.Serialize(writer, obj);
32 }
33 catch(Exception ex)
34 {
35 throw ex;
36 }
37 finally
38 {
39 if(writer != null)
40 writer.Close();
41 }
42 }
43
44 /**////
45 /// 反序列化对象
46 ///

47 /// 文件信息名称 www.Dasixian.com
48 /// 反序列化对象类型
大泗县网,www.DaSixian.Com

49 /// 返回实例化后对象
50 public static object DeSerializeObject(string fileName, Type type)
51 {
52 if (!File.Exists(fileName))
53 return null;
54
55 FileStream fs = null;
56 try
57 {
58 fs = new FileStream(fileName, FileMode.Open);
59
60 XmlSerializer xSer = new XmlSerializer(type);
61 XmlReader reader = new XmlTextReader(fs);
62 return xSer.Deserialize(reader);
63 }
64 catch (Exception ex)
65 {
66 throw ex;
67 }
68 finally
69 {
70 if (fs != null)
71 {
72 fs.Close();
73 }
74 }
75 }
76 #endregion
77 } 大泗县网,www.DaSiXian.com
78}
79


【责任编辑 彭凡】

大泗县 网,www.daSixian.com



发布者:   
 

评论列表

    评论加载中…


大泗县网站 IT频道