【发布时间】:2016-11-02 22:51:54
【问题描述】:
我需要阅读这个 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 类型方面遇到了一些问题。 有人知道我应该使用哪种类型吗? 列表、IList、ICollection、IEnumerable....
非常感谢!
【问题讨论】:
-
您可以尝试创建一个名为 Products 的类,并将产品列表作为其中的属性。然后直接反序列化成产品。
-
嗨,Pratik,你的建议奏效了!非常感谢!
-
很好!!! Kevin.r 秒杀我 :)
-
嗯,还有一个问题,我无法读取属性名称,因为它在产品标签中,所以工作方式不同?有什么解决方法吗?
-
使用名为“Xmlattribute”而不是“xmlement”的名称和属性添加另一个属性。简单!