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