加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML序列化 C#

发布时间:2020-12-16 05:56:11 所属栏目:百科 来源:网络整理
导读:以下为在工作中遇到的需要对类进行XML序列化时用到的代码仅保存已供以后查阅 public static class XmlHelp { public static void SaveToXml(Type type,object sourceObj,string filePath) { if (!string.IsNullOrWhiteSpace(filePath) sourceObj != null) {

以下为在工作中遇到的需要对类进行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; } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读