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

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; }
  }
 }
}
https://www.jb51.net/article/99727.htm

 

posted @ 2020-01-28 14:10  刀小爱  阅读(356)  评论(0)    收藏  举报