0

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?

Rono
  • 3,171
  • 2
  • 33
  • 58

1 Answers1

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