[英]Having issues getting this list from an XML document
I have a xml document I need to serialize into a C# list.我有一个 xml 文档,我需要将其序列化为一个 C# 列表。
<inventory>
<products>
<product name="table" price="29.99" qty="4" />
<product name="chair" price="9.99" qty="7" />
<product name="couch" price="50" qty="2" />
<product name="pillow" price="5" qty="1" />
<product name="bed" price="225.00" qty="1" />
<product name="bench" price="29.99" qty="3" />
<product name="stool" price="19.99" qty="5" />
</products>
I've tried:我试过了:
[XmlRoot("inventory")]
public class Inventory
{
[XmlArray("products")]
[XmlArrayItem("product")]
public List<Product> Products { get; set; }
}
public class Product
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("price")]
public decimal Price { get; set; }
[XmlElement("qty")]
public int Quantity { get; set; }
}
using (StreamReader reader = new StreamReader(path))
{
XmlSerializer serializer = new XmlSerializer(typeof(Product));
products.Add((Product) serializer.Deserialize(reader));
}
Which gives me an InvalidOperationException: was not expected.这给了我一个 InvalidOperationException: 不是预期的。
Any help in this would be great.在这方面的任何帮助都会很棒。
There two things wrong here:这里有两点错误:
Product
, but your XML is an inventory containing multiple products.您正在尝试反序列化单个Product
,但您的 XML 是包含多个产品的库存。 This is what is causing your exception.这就是导致您异常的原因。 You want to deserialise Inventory
你想反序列化Inventory
name
, price
and qty
are XML attributes , not elements name
, price
和qty
是 XML属性,不是元素So amend your Product
class:所以修改你的Product
class:
public class Product
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("price")]
public decimal Price { get; set; }
[XmlAttribute("qty")]
public int Quantity { get; set; }
}
And use the correct serialiser / cast:并使用正确的序列化器/转换:
var serializer = new XmlSerializer(typeof(Inventory));
var inventory = (Inventory)serializer.Deserialize(reader);
See this fiddle for a working demo.有关工作演示,请参阅此小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.