C# XML序列化&反序列化
程序员文章站
2022-03-04 14:21:03
...
类库 System.Xml.Serialization
序列化
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="obj">对象</param>
/// <returns></returns>
public static string Serializer<T>(T obj)
{
string str = string.Empty;
try
{
using (MemoryStream ms = new MemoryStream())
{
XmlTextWriter textWriter = new XmlTextWriter(ms, Encoding.GetEncoding("utf-8"));
XmlSerializer xml = new XmlSerializer(typeof(T));
// 去掉结点的 xmlns:xsi="" 属性
var _namespaces = new XmlSerializerNamespaces(
new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "")
});
//序列化对象
xml.Serialize(textWriter, obj, _namespaces);
str = Encoding.UTF8.GetString(ms.GetBuffer());
}
return str;
}
catch (Exception ex)
{
return str;
}
}
反序列化
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xmlString"></param>
/// <returns></returns>
public static T Deserialize<T>(string xmlString)
{
try
{
using (StringReader st = new StringReader(xmlString))
{
var xmlSer = new XmlSerializer(typeof(T));
return (T)xmlSer.Deserialize(st);
}
}
catch (Exception ex)
{
return default(T);
}
}