[英]How can I read an XML file properly into a collection when the XML has a specific root element name?
我需要阅读以下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对象。 然后可以这样标记您的对象:
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类:
XmlSerializer deserializer = new XmlSerializer(typeof(Products));
没有将类型指定为列表
UPDATE我添加了XmlAttribute(“ Name”)来演示其他问题的解决方案。 @ pratik-gaikwad在我这样做之前就转达了解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.