Deserialize XML with multiple elements into single C# object



I need to deserialize an XML document that looks like:



<Root>
<Items>
<Item>
<ItemHeader Attr1="A" Attr2="B" Attr3="C" />
<ItemDetails Attr4="D" Attr5="E" />
</Item>
...
</Items>
</Root>


Into a class that looks like: [Serializable, XmlRoot("Item")] Public class MyItem { [XmlAttribute("Attr1")] public string Attr1 { get; set; } [XmlAttribute("Attr5")] public string Attr5 { get; set; } }


An I am using the following code to perform the deserialization: XDocument doc; XElement rootElem = doc.Element("Root");



foreach (XElement xe in rootElem.Descendants("Item"))
{
MyItem item = new MyItem();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyItem));
XmlReader xRdr = xe.CreateReader();
item = (MyItem)xmlSerializer.Deserialize(xRdr);


}


However, none of the elements are copied into the object instance.


Is this doable? Do I need to deserialize each sub Element?


Thanks


No comments:

Post a Comment