在 C# 中将泛型集合转换为 XML
Convert a generic collection to a XML in C#
我想编写一个泛型方法,一旦传递了类型 T 的集合,returns 一个 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>
我认为您没有理解 PropertyInfo.GetValue
的参数是什么意思 - 它是 [=23= 的 target ] 获取,而你传递的是 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");
我想编写一个泛型方法,一旦传递了类型 T 的集合,returns 一个 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>
我认为您没有理解 PropertyInfo.GetValue
的参数是什么意思 - 它是 [=23= 的 target ] 获取,而你传递的是 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");