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的方法的詳細內容,更多關於c# 對象序列化XML的資料請關註WalkonNet其它相關文章!

推薦閱讀: