XML序列化、反序列化
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace Manjinba.Communication.Common.Utils
{
public class XmlUtil
{
#region 序列化
/// <summary>
/// 将自定义对象序列化为XML字符串
/// </summary>
/// <param name="myObject">自定义对象实体</param>
/// <returns>序列化后的XML字符串</returns>
public static string SerializeToXml<T>(T myObject)
{
if (myObject != null)
{
XmlSerializer xs = new XmlSerializer(typeof(T));
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
writer.Formatting = Formatting.None;//缩进
xs.Serialize(writer, myObject);
stream.Position = 0;
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
reader.Close();
}
writer.Close();
return sb.ToString();
}
return string.Empty;
}
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="obj">对象</param>
/// <returns></returns>
public static string Serializer(Type type, object obj)
{
MemoryStream Stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(type);
//序列化对象
xml.Serialize(Stream, obj);
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd();
sr.Dispose();
Stream.Dispose();
return str;
}
#endregion
#region 反序列化
/// <summary>
/// 将XML字符串反序列化为对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="xml">XML字符</param>
/// <returns></returns>
public static T DeserializeToObject<T>(string xml)
{
T myObject;
XmlSerializer serializer = new XmlSerializer(typeof(T));
StringReader reader = new StringReader(xml);
myObject = (T)serializer.Deserialize(reader);
reader.Close();
return myObject;
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="xml">XML字符串</param>
/// <returns></returns>
public static object Deserialize(Type type, string xml)
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(sr);
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="xml"></param>
/// <returns></returns>
public static object Deserialize(Type type, Stream stream)
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(stream);
}
#endregion
}
}