XML序列化范序列化(字符串-对象)


public class XMLUtil
{
/// <summary>
/// 把类型T序列化为字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serialObject"></param>
/// <returns></returns>
public static string Serializer<T>(T serialObject) where T : class
{
try {
XmlSerializer ser = new XmlSerializer(typeof(T));
MemoryStream mem = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8);
ser.Serialize(writer, serialObject);
writer.Close();
return Encoding.UTF8.GetString(mem.ToArray());

}
catch (Exception ex)
{
throw new Exception($"序列化对象失败"+ex.Message);
}
}
public static T Descrialize<T>(string str) where T : class
{
try {
XmlSerializer mySerializer = new XmlSerializer(typeof(T));
StreamReader mem2 = new StreamReader(
new MemoryStream(Encoding.UTF8.GetBytes(str)),Encoding.UTF8);
return (T)mySerializer.Deserialize(mem2);
}
catch (Exception ex)
{
throw new Exception("范序列化XML失败:"+ex.Message);
}
}
}

 

通用XML数组序列号

 

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace XmlHelper
{
public static class XmlHelpers
{
/// <summary>
/// object to xml
/// </summary>
/// <param name="obj"></param>
/// <param name="encoding"></param>
/// <returns>xml string</returns>
public static string ToXml(this object obj, string encoding = "utf-8")
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{
Encoding = Encoding.GetEncoding(encoding)
};
using (var s = new MemoryStream())
{
using (var xmlWriter = XmlWriter.Create(s, xmlWriterSettings))
{
var xns = new XmlSerializerNamespaces();
xns.Add("","");
new XmlSerializer(obj.GetType()).Serialize(xmlWriter, obj, xns);
s.Position = 0;
}
using (var sr = new StreamReader(s))
{
return sr.ReadToEnd();
}
}
}

public static T X2Entity<T>(this string obj) where T : class
{
try {
using (StringReader sr = new StringReader(obj))
{
XmlSerializer xmldes = new XmlSerializer(typeof(T));
return xmldes.Deserialize(sr) as T;
}
} catch (Exception ex)
{
throw new Exception("无效的xml串"+ex.Message);
}
}
}
}

posted @ 2021-03-02 10:21  丹心石  阅读(261)  评论(0编辑  收藏  举报