Facundo Laxalde Facundo Laxalde - 1 year ago 53
C# Question

How can I read an XML file properly into a collection when the XML has a specific root element name?

I need to read this xml file:

<?xml version="1.0" encoding="UTF-8"?>
<Product Name="Prod1">
<Description>Desc1</Description >
<Price>100</Price >
<Product Name="Prod2">
<Description>Desc2</Description >
<Price>50</Price >

my idea was do something like this:

public ICollection<ProductDTO> importtProducts()
XmlSerializer deserializer = new XmlSerializer(typeof(List<ProductDTO>));
TextReader textReader = new StreamReader(@"c:\importers\xmlimporter.xml");
List<ProductDTO> prods;
prods = (List<ProductDTO>)deserializer.Deserialize(textReader);
XDocument doc = XDocument.Load(@"c:\importers\xmlimporter.xml");
foreach (var prod in doc.Root.Descendants("Product").Distinct())
//work with the prod in here
return some prods..;

but I'm having some problems with the root item, the xmlSerializer type.
does someone know which type should I use?
List, IList, ICollection, IEnumerable....

thanks a lot!

Answer Source

Consider creating one Products object with a List. You can then mark your objects as such:

public class Products
  [XmlElement("Product", Type = typeof(Product))]
  public List<Product> Products { get; set; }

public class Product
  public string Name { get; set; }

  public string Description { get; set; }


This will generate to a Products class that has a list of type Product when using:

XmlSerializer deserializer = new XmlSerializer(typeof(Products));

without specifying the type as a list

UPDATE I added XmlAttribute("Name") to demonstrate the solution to the additional issue. @pratik-gaikwad relayed the solution before I did.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download