从 XML 文档获取此列表时遇到问题
Having issues getting this list from an XML document
我有一个 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>
我试过:
[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));
}
这给了我一个 InvalidOperationException: 不是预期的。
这方面的任何帮助都会很棒。
这里有两处错误:
- 您正在尝试反序列化单个
Product
,但您的 XML 是包含多个产品的库存。这就是导致您异常的原因。你想反序列化 Inventory
name
、price
和 qty
是 XML 属性 ,而不是 元素
所以修改你的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; }
}
并使用正确的序列化器/转换:
var serializer = new XmlSerializer(typeof(Inventory));
var inventory = (Inventory)serializer.Deserialize(reader);
有关工作演示,请参阅 this fiddle。
我有一个 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>
我试过:
[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));
}
这给了我一个 InvalidOperationException: 不是预期的。
这方面的任何帮助都会很棒。
这里有两处错误:
- 您正在尝试反序列化单个
Product
,但您的 XML 是包含多个产品的库存。这就是导致您异常的原因。你想反序列化Inventory
name
、price
和qty
是 XML 属性 ,而不是 元素
所以修改你的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; }
}
并使用正确的序列化器/转换:
var serializer = new XmlSerializer(typeof(Inventory));
var inventory = (Inventory)serializer.Deserialize(reader);
有关工作演示,请参阅 this fiddle。