当XML具有特定的根元素名称时,如何将XML文件正确读入集合?

时间:2016-11-02 22:51:55

标签: c# xml linq

我需要阅读这个xml文件:

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

我的想法是做这样的事情:

        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..;
    }

但是我对根项目xmlSerializer类型有一些问题。 有人知道我应该使用哪种类型? List,IList,ICollection,IEnumerable ....

非常感谢!

1 个答案:

答案 0 :(得分:4)

考虑使用List创建一个Products对象。然后,您可以将对象标记为:

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

  ...
}

这将生成一个Products类,它在使用时具有Product类型列表:

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

未将类型指定为列表

<强>更新 我添加了XmlAttribute(“Name”)来演示其他问题的解决方案。 @ pratik-gaikwad在我做之前传达了解决方案。