栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

c#序列化对象与反序列化

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c#序列化对象与反序列化

1 反序列化函数定义

public object deSerialize(string filePath, Type type)
{
     object t = null;

     if (File.Exists(filePath))
     {
          using (StreamReader reader = new StreamReader(filePath))
          {
              System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
              t = xmlSerializer.Deserialize(reader);
          }
      }
      return t;
}

2 序列化函数定义

public void saveToXml(string filePath, object sourceObj, Type type, string rootName)
{
      if (File.Exists(filePath) && sourceObj != null)
      {
          using (StreamWriter writer = new StreamWriter(filePath))
          {
              type = type != null ? type : sourceObj.GetType();
              System.Xml.Serialization.XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(rootName) ?
              new System.Xml.Serialization.XmlSerializer(type) : new System.Xml.Serialization.XmlSerializer(type, new System.Xml.Serialization.XmlRootAttribute(rootName));
              xmlSerializer.Serialize(writer, sourceObj);
          }
    }
}
  

解释:

filename 是 xml 文件的根目录

sourceObj 是源对象 一般为类的一个对象

type 为 源对象的类型

rootname 为根文件名 可自定义 也可不自定义

一个复杂的xml文件如下

This XML file does not appear to have any style information associated with it. The document tree is shown below.


	
		euoqejadj   //element  水平结构
	

	
		NIKE
	


	   //root
		   //  element
			   //list   root

				   // element
					  // list root

						429485-95478025402502  //xmlAttribute (...baidu.com)   42....是xmlText    
						429485-95478025402502


					
				

				
					

						429485-95478025402502
						429485-95478025402502
					
					
				

			
			
	

其中 :

为文件根目录 根目录不止有一个

表现为水平结构 如    

List T代表泛型 一般为类名 

表现为 primaryIdentifier=" value ";

表现为   value  

参考:

C#对象XML序列化(一):序列化方法和常用特性 - K.W - 博客园

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/873844.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号