C# XML反序列化与序列化
1、首先我们建一个XmlUtil类,然后,提供四个方法,对字符串和文件进入反序列化与序列化
2、添加 将XML字符串反序列化成对象 方法肥蹲
public static T Deserialize<T>(string xml, string xmlRootName = "Root")
{
T result = default(T);
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?
new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName));
裕鬼泪 result = (T)xmlSerializer.Deserialize(sr);
}
return result;
}
3、添加 将XML文件反序列化成对象 方法
public static T DeserializeFile<T>(string filePath, string xmlRootName = "Root")
{
T result = default(T);
if (File.Exists(filePath))
{
using (StreamReader reader = new StreamReader(filePath))
{
获阅 XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?
new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName));
result = (T)xmlSerializer.Deserialize(reader);
}
}
return result;
}
4、添加 将对象序列化成XML字符串 方法
public static string Serializer(object sourceObj, string xmlRootName = "Root")
{
MemoryStream Stream = new MemoryStream();
Type type = sourceObj.GetType();
XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?
new XmlSerializer(type) : new XmlSerializer(type, new XmlRootAttribute(xmlRootName));
xmlSerializer.Serialize(Stream, sourceObj);
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd();
sr.Dispose();
Stream.Dispose();
return str;
}
5、添加 将对象序列化成XML文件 方法
public static void SerializerFile(string filePath, object sourceObj, string xmlRootName = "Root")
{
if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)
{
Type type = sourceObj.GetType();
using (StreamWriter writer = new StreamWriter(filePath))
{
XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?
new XmlSerializer(type) : new XmlSerializer(type, new XmlRootAttribute(xmlRootName));
xmlSerializer.Serialize(writer, sourceObj);
}
}
}
6、对字符串的序列化与反序列化测试
// 序列化
string strTmp = XmlUtil.Serializer(data);
// 反序列化
Data tmpData = XmlUtil.Deserialize<Data>(strTmp);
7、对文件的序列化与反序列化测试
// 序列化
XmlUtil.SerializerFile("./guoke.xml",list);
// 反序列化
List<Data> tmpList = XmlUtil.DeserializeFile<List<Data>>("./guoke.xml");