需要添加的命名空间:
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.youkuaiyun.com/wangzl1163/article/details/71195072
本文介绍了一个使用C#进行XML序列化和反序列化的实用类XMLHelper。该类提供了两个主要方法:CreateXML用于将任意类型对象转换为XML文件;Deserialize用于从XML字符串中读取并转换为指定类型的对象。
4222

被折叠的 条评论
为什么被折叠?



