中南财经政法大学论坛

 找回密码
 注册(开放注册)
搜索
查看: 1539|回复: 0
打印 上一主题 下一主题

[应用技术] Xml 串行话对象与反串行实例

[复制链接]
跳转到指定楼层
1#
发表于 2007-11-10 14:39:22 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
一个简单的例子,但是很实用。将对象直接串行话为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 /// 文件信息名称
21 /// 待序列化对象
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 /// 文件信息名称
48 /// 反序列化对象类型
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 }
78}
79
您需要登录后才可以回帖 登录 | 注册(开放注册)

本版积分规则

手机访问本页请
扫描左边二维码
         本网站声明
本网站所有内容为网友上传,若存在版权问题或是相关责任请联系站长!
站长联系QQ:7123767   myubbs.com
         站长微信:7123767
请扫描右边二维码
www.myubbs.com

小黑屋|手机版|Archiver|中南财经政法大学论坛 ( 琼ICP备10001196号-2 )

GMT+8, 2024-4-25 20:23 , Processed in 0.035273 second(s), 15 queries .

Powered by 高考信息网 X3.3

© 2001-2013 大学排名

快速回复 返回顶部 返回列表