XML序列化 C#
2016-02-19 14:20
330 查看
以下为在工作中遇到的需要对类进行XML序列化时用到的代码仅保存已供以后查阅
public static class XmlHelp
{
public static void SaveToXml(Type type,object sourceObj,string filePath)
{
if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)
{
type = type != null ? type : sourceObj.GetType();
using (StreamWriter writer = new StreamWriter(filePath))
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type) ;
xmlSerializer.Serialize(writer, sourceObj);
}
}
}
public static object LoadFromXml(Type type,string filePath)
{
object result = null;
if (File.Exists(filePath))
{
using (StreamReader reader = new StreamReader(filePath))
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
result = xmlSerializer.Deserialize(reader);
}
}
return result;
}
}
public static class XmlHelp
{
public static void SaveToXml(Type type,object sourceObj,string filePath)
{
if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)
{
type = type != null ? type : sourceObj.GetType();
using (StreamWriter writer = new StreamWriter(filePath))
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type) ;
xmlSerializer.Serialize(writer, sourceObj);
}
}
}
public static object LoadFromXml(Type type,string filePath)
{
object result = null;
if (File.Exists(filePath))
{
using (StreamReader reader = new StreamReader(filePath))
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
result = xmlSerializer.Deserialize(reader);
}
}
return result;
}
}
相关文章推荐
- C# 3D到2D投射
- C# 洗牌算法
- C#资源释放方法实例分析
- C# 中DateTime的各种使用
- C#获取泛型集合中元素的类型
- 远程桌面,RDP文件密码加密、解密算法(C#)
- csharp:正则表达式采集网页数据
- c# out ref
- C#泛型集合之Dictionary使用技巧
- c#中的数据类型简介(string)
- 解析C#设计模式编程中外观模式Facade Pattern的应用
- byte数组与Image的相互转换
- C#委托&事件
- c# word 操作
- C#如何释放已经加载的图片
- 使用C#配合ArcGIS Engine进行地理信息系统开发
- 浅谈基类与子类之间继承关系
- C#多线程简单例子讲解
- C#中的线程(一)入门
- c#实现每隔一段时间执行代码(多线程)