I need to parse XML responses into different class objects. I have classes with many different properties. I know I can create the objects directly using LINQ like the below code:
XElement response = XElement.Parse(xmlValue);
IEnumerable<DTO> result =
from el in response.Descendants("i")
select new DTO()
{
Object_ID = (int)el.Attribute("Object_ID")
// Other properties mapped here.
};
My XML is is the following format and only has attribute values, no element values:
<root>
<i attribute1="value" attribute2="value"... attributex="value"/>
<i attribute1="value" attribute2="value"... attributex="value"/>
<i attribute1="value" attribute2="value"... attributex="value"/>
<i attribute1="value" attribute2="value"... attributex="value"/>
</root>
The issue is that I have multiple DTO's and I don't want to write different handlers for each case since there are so many different attributes and mapping each attribute would result in redundant ugly code.
I need the data to be stored in an IEnumerable type.
Is this the most efficient way to proceed? Should I create a generic type conversion method that returns objects?
EDIT: I eventually used XmlSerializer to solve this problem, with a few minor adjustments to the accepted answer below. Code follows:
public static IEnumerable<T> DeserializeXml<T>(XElement response)
{
var list = new List<T>();
foreach (var item in response.Descendants("i"))
{
using (var sr = new StringReader(student.ToString()))
{
var xRoot = new XmlRootAttribute();
xRoot.ElementName = "i";
xRoot.IsNullable = true;
var serializer = new XmlSerializer(typeof(T), xRoot);
list.Add((T)serializer.Deserialize(sr));
}
}
return list;
}