Facundo Laxalde Facundo Laxalde - 8 months ago 37
C# Question

Read XML file properly c# linq

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!


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 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