Facundo Laxalde Facundo Laxalde - 1 month ago 5
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"?>
<Products>
<Product Name="Prod1">
<Description>Desc1</Description >
<Price>100</Price >
<Stock>200</Stock>
</Product>
<Product Name="Prod2">
<Description>Desc2</Description >
<Price>50</Price >
<Stock>400</Stock>
</Product>
</Products>


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);
textReader.Close();
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

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
{
  [XmlAttribute("Name")]
  public string Name { get; set; }

  [XmlElement("Description")]
  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.