這篇文章給大家介紹如何在C#項目中實現對象序列化XML,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
首先,需要用到的是這兩個命名空間(主要)
using System.Xml; using System.Xml.Serialization;
然后序列化和反序列化的方式和Json一樣。(后面提供封裝方法)
string result = XmlSerializeHelper.Serialize<test>(new test
{
name = "Seven",
cardId = "663927",
age = 15,
currentTime = DateTime.Now
});
Console.WriteLine(result);
test test2 = XmlSerializeHelper.DeSerialize<test>(result);
下面來看封裝類
public class XmlSerializeHelper
{
//對象轉XML
public static string ObjToXml(object obj)
{
using (MemoryStream Stream = new MemoryStream())
{
XmlSerializer xml = new XmlSerializer(obj.GetType());
xml.Serialize(Stream, obj);
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
return sr.ReadToEnd();
}
}
public static string Serialize<T>(T obj)
{
return Serialize<T>(obj, Encoding.UTF8);
}
/// <summary>
/// 實體對象序列化成xml字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string Serialize<T>(T obj, Encoding encoding)
{
try
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
var ser = new XmlSerializer(obj.GetType());
using (var ms = new MemoryStream())
{
using (var writer = new XmlTextWriter(ms, encoding))
{
writer.Formatting = Formatting.Indented;
ser.Serialize(writer, obj);
}
var xml = encoding.GetString(ms.ToArray());
xml = xml.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
xml = xml.Replace("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "");
xml = Regex.Replace(xml, @"\s{2}", "");
xml = Regex.Replace(xml, @"\s{1}/>", "/>");
return xml;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 反序列化xml字符為對象,默認為Utf-8編碼
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns></returns>
public static T DeSerialize<T>(string xml) where T : new()
{
return DeSerialize<T>(xml, Encoding.UTF8);
}
/// <summary>
/// 反序列化xml字符為對象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static T DeSerialize<T>(string xml, Encoding encoding) where T : new()
{
try
{
var mySerializer = new XmlSerializer(typeof(T));
using (var ms = new MemoryStream(encoding.GetBytes(xml)))
{
using (var sr = new StreamReader(ms, encoding))
{
return (T)mySerializer.Deserialize(sr);
}
}
}
catch (Exception e)
{
return default(T);
}
}
}
Class Of XmlSerializeHelper關于如何在C#項目中實現對象序列化XML就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。