在工作中,如果需要跟XML打交道,难免会遇到需要把一个类型集合转换成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));
}
///
/// 集合转换成数据表
///
/// 泛型参数(集合成员的类型)
/// 泛型集合
/// 集合的XML格式字符串
public static string CollectionToXml(IEnumerable TCollection)
{
//定义元素数组
var elements = new List();
//把集合中的元素添加到元素数组中
foreach (var item in TCollection)
{
//获取泛型的具体类型
Type type = typeof(T);
//定义属性数组,XObject是XAttribute和XElement的基类
var attributes = new List();
//获取类型的所有属性,并把属性和值添加到属性数组中
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();
}
///
/// 人类(测试数据类)
///
class Person
{
///
/// 名称
///
public string Name { get; set; }
///
/// 年龄
///
public int Age { get; set; }
}
}
}
把属性作为属性输出:
把属性作为子元素输出:
李元芳 23狄仁杰 32
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持考高分网!



