【问题标题】:How can I read an XML file properly into a collection when the XML has a specific root element name?当 XML 具有特定的根元素名称时,如何将 XML 文件正确读取到集合中?
【发布时间】: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”的名称和属性添加另一个属性。简单!

标签: c# xml linq


【解决方案1】:

考虑创建一个带有列表的 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; }

  ...
}

这将在使用时生成具有 Product 类型列表的 Products 类:

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

不指定类型为列表

更新 我添加了 XmlAttribute("Name") 来演示附加问题的解决方案。 @pratik-gaikwad 在我之前转发了解决方案。

【讨论】:

  • 嗯,还有一个问题,我无法读取属性名称,因为它在产品标签中,所以工作方式不同?有什么解决方法吗?
  • 很高兴我能帮上忙。我已经打过几次 XML 之战了,我很同情你。
猜你喜欢
  • 2013-10-09
  • 2019-12-28
  • 1970-01-01
  • 2013-09-12
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多