当XML具有特定的根元素名称时

当XML具有特定的根元素名称时

本文介绍了当XML具有特定的根元素名称时,如何将XML文件正确地读取到集合中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要阅读以下xml文件:

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

但是我的根项目xmlSerializer类型遇到了一些问题.有人知道我应该使用哪种类型吗?列表,IList,ICollection,IEnumerable ....

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

非常感谢!

推荐答案

请考虑使用列表创建一个Products对象.然后,您可以像这样标记您的对象:

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

  ...
}

使用以下方法时,这将生成一个包含产品类型列表的Products类:

This will generate to a Products class that has a list of type Product when using:

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

未将类型指定为列表

更新我添加了XmlAttribute("Name")来演示其他问题的解决方案. @ pratik-gaikwad在我这样做之前就转达了解决方案.

UPDATEI added XmlAttribute("Name") to demonstrate the solution to the additional issue. @pratik-gaikwad relayed the solution before I did.

这篇关于当XML具有特定的根元素名称时,如何将XML文件正确地读取到集合中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 10:36