在C#中将泛型集合转换为XML

时间:2015-07-26 11:15:37

标签: c# xml generics reflection

我想编写一个泛型方法,一旦传递了类型T的集合就返回XML。我试过下面的代码,但没有按预期工作。任何有关增强此功能以包含元素属性的建议都非常受欢迎。谢谢

public XElement GetXElements<T>(IEnumerable<T> colelction,string parentNodeName) where T : class
{            
    XElement xml = new XElement(typeof(T).GetType().Name);
    foreach(var x in typeof(T).GetProperties())
    {
        var name = x.Name;
        var value = typeof(T).GetProperty(x.Name).GetValue(x);
        xml.Add(new XElement(name,value));
    }         
    return xml;
}

例如,如果我将上面的集合发送到上面的方法,

        var col = new List<Employee>()
        {
            new Employee
            {
                FirstName = "John",
                Sex= "Male"
            },
            new Employee
            {
                FirstName = "Lisa",
                Sex= "Female"
            },
        };

并将方法调用为GetXElements<Employee>(col,"Employees")我希望获得如下所示的XML

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee>
     <FirstName>John</FirstName>
     <Sex>Male</Sex>
  </Employee>
  <Employee>
     <FirstName>Lisa</FirstName>
     <Sex>Female</Sex>
  </Employee>
<Employees>

1 个答案:

答案 0 :(得分:1)

我不认为你已经明白PropertyInfo.GetValue的论点是什么 - 它意味着属性的目标获取,而您正在传递PropertyInfo本身。

此外,您的方法只有一个参数,而您尝试传入两个参数。我想你想要这样的东西:

public static XElement GetXElements<T>(IEnumerable<T> collection, string wrapperName)
    where T : class
{
    return new XElement(wrapperName, collection.Select(GetXElement));
}

private static XElement GetXElement<T>(T item)
{
    return new XElement(typeof(T).Name,
        typeof(T).GetProperties()
                 .Select(prop => new XElement(prop.Name, prop.GetValue(item, null));
}

这会给出您正在寻找的结果。请注意,在调用GetXElement时,您不需要指定类型参数,因为类型推断会做正确的事情:

XElement element = GetXElements(col,"Employees");
相关问题