I am attempting to find .NET code to convert a list of anonymous objects to an XML string, but have failed so far. The anonymous objects do not contain any sub lists, it's just a set of values. The XmlSerializer class throws an exception if an anonymous type is passed to it. Can anyone provide code to do this?
Asked
Active
Viewed 25 times
0
-
https://stackoverflow.com/questions/2404685/can-i-serialize-anonymous-types-as-xml/2404984#2404984 Could this help you? – Darius Pintilie Jun 03 '19 at 16:27
1 Answers
0
Writing a function do do that was fairly simple:
public XElement ListToXML<T>(List<T> list)
{
var result = new XElement("Data");
var props = typeof(T).GetProperties();
foreach (var item in list)
{
var line = new XElement("Record");
foreach (var prop in props)
{
var value = prop.GetValue(item);
var element = new XElement(prop.Name, value);
line.Add(element);
}
result.Add(line);
}
return result;
}

Rono
- 3,171
- 2
- 33
- 58