C# 中对象序列化XML的方法

今天我们来看一下在C#中对象序列化XML的方法。

不得不说,在这个Json横行的年代,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的方法 的全部内容, 来源链接: utcz.com/z/322926.html

回到顶部