I have a xml document I need to serialize into a C# list.
<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.
Any help in this would be great.
CodePudding user response:
There two things wrong here:
- you are trying to deserialise a single
Product
, but your XML is an inventory containing multiple products. This is what is causing your exception. You want to deserialiseInventory
name
,price
andqty
are XML attributes, not elements
So amend your 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.