您的位置:首页 > 编程语言 > C#

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;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: