C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串的方法
在工作中,如果需要跟XML打交道,难免会遇到需要把一个类型集合转换成XML格式的情况。之前的方法比较笨拙,需要给不同的类型,各自写一个转换的函数。但是后来接触反射后,就知道可以利用反射去读取一个类型的所有成员,也就意味着可以替不同的类型,创建更通用的方法。这个例子是这样做的:利用反射,读取一个类型的所有属性,然后再把属性转换成XML元素的属性或者子元素。下面注释比较完整,就话不多说了,有需要看代码吧!
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Xml.Linq;
usingSystem.Reflection;
namespaceGenericCollectionToXml
{
classProgram
{
staticvoidMain(string[]args)
{
varpersons=new[]{
newPerson(){Name="李元芳",Age=23},
newPerson(){Name="狄仁杰",Age=32}
};
Console.WriteLine(CollectionToXml(persons));
}
///<summary>
///集合转换成数据表
///</summary>
///<typeparamname="T">泛型参数(集合成员的类型)</typeparam>
///<paramname="TCollection">泛型集合</param>
///<returns>集合的XML格式字符串</returns>
publicstaticstringCollectionToXml<T>(IEnumerable<T>TCollection)
{
//定义元素数组
varelements=newList<XElement>();
//把集合中的元素添加到元素数组中
foreach(variteminTCollection)
{
//获取泛型的具体类型
Typetype=typeof(T);
//定义属性数组,XObject是XAttribute和XElement的基类
varattributes=newList<XObject>();
//获取类型的所有属性,并把属性和值添加到属性数组中
foreach(varpropertyintype.GetProperties())
//获取属性名称和属性值,添加到属性数组中(也可以作为子元素添加到属性数组中,只需把XAttribute更改为XElement)
attributes.Add(newXAttribute(property.Name,property.GetValue(item,null)));
//把属性数组添加到元素中
elements.Add(newXElement(type.Name,attributes));
}
//初始化根元素,并把元素数组作为根元素的子元素,返回根元素的字符串格式(XML)
returnnewXElement("Root",elements).ToString();
}
///<summary>
///人类(测试数据类)
///</summary>
classPerson
{
///<summary>
///名称
///</summary>
publicstringName{get;set;}
///<summary>
///年龄
///</summary>
publicintAge{get;set;}
}
}
}
把属性作为属性输出:
<Root> <PersonName="李元芳"Age="23"/> <PersonName="狄仁杰"Age="32"/> </Root>
把属性作为子元素输出:
<Root> <Person> <Name>李元芳</Name> <Age>23</Age> </Person> <Person> <Name>狄仁杰</Name> <Age>32</Age> </Person> </Root>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!