C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串的方法

时间:2022-01-19 16:34:53

在工作中,如果需要跟XML打交道,难免会遇到需要把一个类型集合转换成XML格式的情况。之前的方法比较笨拙,需要给不同的类型,各自写一个转换的函数。但是后来接触反射后,就知道可以利用反射去读取一个类型的所有成员,也就意味着可以替不同的类型,创建更通用的方法。这个例子是这样做的:利用反射,读取一个类型的所有属性,然后再把属性转换成XML元素的属性或者子元素。下面注释比较完整,就话不多说了,有需要看代码吧!

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Reflection;
namespace GenericCollectionToXml
{
 class Program
 {
  static void Main(string[] args)
  {
   var persons = new[]{
    new Person(){Name="李元芳",Age=23},
    new Person(){Name="狄仁杰",Age=32}
   };
   Console.WriteLine(CollectionToXml(persons));
  }
  /// <summary>
  /// 集合转换成数据表
  /// </summary>
  /// <typeparam name="T">泛型参数(集合成员的类型)</typeparam>
  /// <param name="TCollection">泛型集合</param>
  /// <returns>集合的XML格式字符串</returns>
  public static string CollectionToXml<T>(IEnumerable<T> TCollection)
  {
   //定义元素数组
   var elements = new List<XElement>();
   //把集合中的元素添加到元素数组中
   foreach (var item in TCollection)
   {
    //获取泛型的具体类型
    Type type = typeof(T);
    //定义属性数组,XObject是XAttribute和XElement的基类
    var attributes = new List<XObject>();
    //获取类型的所有属性,并把属性和值添加到属性数组中
    foreach (var property in type.GetProperties())
     //获取属性名称和属性值,添加到属性数组中(也可以作为子元素添加到属性数组中,只需把XAttribute更改为XElement)
     attributes.Add(new XAttribute(property.Name, property.GetValue(item, null)));
    //把属性数组添加到元素中
    elements.Add(new XElement(type.Name, attributes));
   }
   //初始化根元素,并把元素数组作为根元素的子元素,返回根元素的字符串格式(XML)
   return new XElement("Root", elements).ToString();
  }
  /// <summary>
  /// 人类(测试数据类)
  /// </summary>
  class Person
  {
   /// <summary>
   /// 名称
   /// </summary>
   public string Name { get; set; }
   /// <summary>
   /// 年龄
   /// </summary>
   public int Age { get; set; }
  }
 }
}

把属性作为属性输出:

?
1
2
3
4
<Root>
 <Person Name="李元芳" Age="23" />
 <Person Name="狄仁杰" Age="32" />
</Root>

把属性作为子元素输出:

?
1
2
3
4
5
6
7
8
9
10
<Root>
 <Person>
 <Name>李元芳</Name>
 <Age>23</Age>
 </Person>
 <Person>
 <Name>狄仁杰</Name>
 <Age>32</Age>
 </Person>
</Root>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持服务器之家!