1、xml序列化
public static string SerializeXml(object data)
{
using (StringWriter sw = new StringWriter())
{
XmlSerializer xz = new XmlSerializer(data.GetType());
xz.Serialize(sw, data);
return sw.ToString();
}
}
public static void SerializeToXml(object o, string xmlFileName)
{
var type = o.GetType(); if (o == null) { return; }
string lastDirectoryPath = Path.GetDirectoryName(xmlFileName);
if (!Directory.Exists(lastDirectoryPath))
{
Directory.CreateDirectory(lastDirectoryPath);
}
//序列化对象
XmlSerializer serializer = new XmlSerializer(type);
using (XmlTextWriter xtw = new XmlTextWriter(xmlFileName, Encoding.UTF8))
{
//用XmlTextWriter 创建一个XML文件
xtw.Formatting = Formatting.Indented;
//可实现换行显示
serializer.Serialize(xtw, o);
}
}
public static MemoryStream SerializeXml(object data, Encoding encoding)
{
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms, encoding);
XmlSerializer xz = new XmlSerializer(data.GetType());
xz.Serialize(sw, data);
return ms;
}
2、xml反序列化
public static T DeserializeXml<T>(string xmlFileName)
{
FileStream fs = File.Open(xmlFileName, FileMode.Open);
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{
XmlSerializer xz = new XmlSerializer(typeof(T));
T dept = (T)xz.Deserialize(sr);
return dept;
}
}