XML序列化 C#

前端之家收集整理的这篇文章主要介绍了XML序列化 C#前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

猜你在找的XML相关文章