亲宝软件园·资讯

展开

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

王月半子 人气:0
想了解C# 中对象序列化XML的方法的相关内容吗,王月半子在本文为您仔细讲解c# 对象序列化XML的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:c#,对象序列化,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

好了,板砖要紧,先到这里。

加载全部内容

相关教程
猜你喜欢
用户评论