c#对对象进行序列化和反序列化
程序员文章站
2022-06-16 12:34:55
...
需要添加的命名空间:
using System.IO;
using System.Xml.Serialization;
using System.Xml;
namespace XMLTest {
public class XMLHelper
{
public bool CreateXML<T>(T obj, string path) {
XmlWriter write = null;
XmlWriterSettings setting = new XmlWriterSettings()
{
Indent = true,
Encoding = Encoding.UTF8
};
try
{
write = XmlWriter.Create(path, setting);
}
catch (Exception)
{
return false;
}
XmlSerializer xml = new XmlSerializer(typeof(T));
try
{
xml.Serialize(write, obj);
}
catch (Exception)
{
return false;
}
finally
{
write.Close();
}
return true;
}
public Object Deserialize(string path,Type type) {
string xmlString = File.ReadAllText(path);
if (string.IsNullOrEmpty(xmlString))
{
return null;
}
else {
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
{
XmlSerializer xml = new XmlSerializer(type);
try
{
return xml.Deserialize(stream);
}
catch (Exception)
{
return null;
}
}
}
}
}
}
原文参考:https://blog.csdn.net/wangzl1163/article/details/71195072