I know this is an old question, but today I struggled with it and found an answer that does not require encapsulation.
Assumption 1: You have control over the original Xml and its construction.
Assumption 2: You are trying to serialize Xml directly to a List<T> object
- You must specify the Root element in Xml as
ArrayOfxxx , where xxx is the name of your class (or the name specified in XmlType (see 2.)) - If you want your xml Elements to have a different name for the class, you should use
XmlType in the class.
NB: If your type name (or class name) begins with a lowercase letter, you must convert the first character to uppercase.
Example 1 - Without XmlType
class Program { static void Main(string[] args) { //String containing the xml array of items. string xml = @"<ArrayOfItem> <Item> <Name>John Doe</Name> </Item> <Item> <Name>Martha Stewart</Name> </Item> </ArrayOfItem>"; List<Item> items = null; using (var mem = new MemoryStream(Encoding.Default.GetBytes(xml))) using (var stream = new StreamReader(mem)) { var ser = new XmlSerializer(typeof(List<Item>)); //Deserialising to List<Item> items = (List<Item>)ser.Deserialize(stream); } if (items != null) { items.ForEach(I => Console.WriteLine(I.Name)); } else Console.WriteLine("No Items Deserialised"); } } public class Item { public string Name { get; set; } }
Example 2 - With XmlType
class Program { static void Main(string[] args) { //String containing the xml array of items. //Note the Array Name, and the Title case on stq. string xml = @"<ArrayOfStq> <stq> <Name>John Doe</Name> </stq> <stq> <Name>Martha Stewart</Name> </stq> </ArrayOfStq>"; List<Item> items = null; using (var mem = new MemoryStream(Encoding.Default.GetBytes(xml))) using (var stream = new StreamReader(mem)) { var ser = new XmlSerializer(typeof(List<Item>)); //Deserialising to List<Item> items = (List<Item>)ser.Deserialize(stream); } if (items != null) { items.ForEach(I => Console.WriteLine(I.Name)); } else Console.WriteLine("No Items Deserialised"); } } [XmlType("stq")] public class Item { public string Name { get; set; } }
source share