基于.net core封装的xml序列化,反序列化操作

需求:

  由于在.net core中去除了Xml序列化XmlSerializer操作类。因此,在于一此数据传输当中出,需要用到对xml格式字符串的处理问题。因此封装了一个xml序列化与反序列化操作的类库。

功能:

1.将一个普通对象序列化为一个xml,并将其对应的xml格式反序列化为该对象;

2.将一个数组集合对象序列化为一个xml,并将其对应的xml格式反序列化为该对象;

3.将一个泛型集合对象序列化为一个xml,并将其对应的xml格式反序列化为该对象;

代码片段:

主要类为:XmlSerializer<T>,其中主要方法:

1.将对象序列化为xml的方法:ToXml(T packet)

 1 /// <summary>
 2 /// 序列化报文为xml
 3 /// </summary>
 4 /// <param name="packet"></param>
 5 /// <returns></returns>
 6 public string ToXml(T packet)
 7 {
 8     StringBuilder sb = new StringBuilder();
 9     if (!string.IsNullOrEmpty(_xmlHead))
10     {
11         sb.AppendFormat("{0}\r\n", _xmlHead);
12     }
13     try
14     {
15         Visit(sb, packet);
16     }
17     catch (Exception ex)
18     {
19         throw new XmlSerializerException($"序列化对象异常:{ex.Message}", ex);
20     }
21     return sb.ToString();
22 }

2.将xml内容反序列为对象T的操作:FromXml(string xml)

 1 /// <summary>
 2 /// 序列化为报文内容
 3 /// </summary>
 4 /// <param name="xml"><packet>标签开始的xml内容</param>
 5 /// <returns></returns>
 6 public T FromXml(string xml)
 7 {
 8     int index;
 9     if (xml.Trim().StartsWith("<?xml") && (index = xml.IndexOf("?>")) != -1)
10     {
11         xml = xml.Substring(index + 2).Trim('\r', '\n', ' ');
12     }
13     try
14     {
15         switch (_elemType)
16         {
17             case ElementType.Generic:
18                 return VisitXmlGeneric(xml);
19             case ElementType.Array:
20                 return VisitXmlArray(xml);
21             default:
22                 return VisitXmlObject(xml);
23         }
24     }
25     catch (Exception ex)
26     {
27         throw new XmlSerializerException($"反序列化对象信息异常:{ex.Message}", ex);
28     }
29 }

使用示例:

 1 // CreatedBy: Jackie Lee(天宇遊龍)
 2 // CreatedOn: 2017-04-13
 3 // 博客:http://www.cnblogs.com/dralee
 4 /// <summary>
 5 /// 测试类
 6 /// </summary>
 7 public class PersonTest
 8 {
 9     public void Test()
10     {
11         Person p1 = new Person
12         {
13             Id = 1,
14             Name = "Jackie",
15             Gender = Gender.Male,
16             Phone = "18412345678",
17             Address = new Address { Province = "广东", City = "深圳", Detail = "xx区xx街道xxxx号" }
18         };
19         Person p2 = new Person
20         {
21             Id = 2,
22             Name = "Hony",
23             Gender = Gender.Female,
24             Phone = "13512345678",
25             Address = new Address { Province = "广东", City = "深圳", Detail = "yy区yy街道yyyy号" }
26         };
27 
28         XmlSerializer<Person> xs = new XmlSerializer<Person>("<?xml version=\"1.0\" encoding=\"utf - 8\"?>");
29         var xml1 = xs.ToXml(p1);
30         OutPrint("对象序列化", xml1);
31         var xml2 = xs.ToXml(p2);
32         OutPrint("xml反序列化", xml2);
33 
34         Console.WriteLine("\r\n============= 数组对象 ===============");
35 
36         var pArr = new Person[] { p1, p2 };
37         XmlSerializer<Person[]> xsArr = new XmlSerializer<Person[]>("");
38         var xml4 = xsArr.ToXml(pArr);
39         OutPrint("数组对象序列化", xml4);
40 
41         var pArr2 = xsArr.FromXml(xml4);
42         Console.WriteLine("============= 数组对象反序列化 ===============");
43         pArr2.ToList().ForEach(p =>
44         {
45             OutPrint("数组对象", p.ToString());
46         });
47 
48         Console.WriteLine("\r\n============= 泛型集合对象 ===============");
49         var ps = new List<Person> { p1, p2 };
50         XmlSerializer<List<Person>> xsList = new XmlSerializer<List<Person>>("");
51         var xml3 = xsList.ToXml(ps);
52         OutPrint("泛型集合对象序列化", xml3);
53 
54         var ps2 = xsList.FromXml(xml3);
55         Console.WriteLine("============= 泛型集合对象反序列化 ===============");
56         ps2.ForEach(p =>
57         {
58             OutPrint("泛型集合对象", p.ToString());
59         });
60     }
61 
62     private void OutPrint(string tip, string msg)
63     {
64         Console.WriteLine("======>{0}:", tip);
65         Console.WriteLine(msg);
66     }
67 }

运行效果:

 

  

类库文件: FD.Generic.Xml.zip

项目源代码已上传github,点击查看源码:https://github.com/dralee/FDGenericXml

SamYau2014反映,已添加对CDATA值的支持,源码见github

新版本效果:

 

posted @ 2017-04-13 18:34  遊龍  阅读(5931)  评论(1编辑  收藏  举报