So I have a client that needs to interchange some XML data with a customer. The XML document exchanged is fairly hierarchical except for one field.
This fragment of XML represents the flat structure:
<ShipFrom>
<Name />
</ShipFrom>
<LineItem>
<Qty>0</Qty>
<ItemId>Item A</ItemId>
<Serial>1234</Serial>
<ReceivedQty>1</ReceivedQty>
</LineItem>
<LineItem>
<Qty>0</Qty>
<ItemId>Item B</ItemId>
<Serial>3211</Serial>
<ReceivedQty>1</ReceivedQty>
</LineItem>
<OrderTrailer>
<TotalQty>1</TotalQty>
</OrderTrailer>
I have a nice object hierachy that deserializes this XML to a set of properties (sub objects). However the LineItem nodes really should be surrounded by a parent node to better represent an array or list of these items. The customer can not change their end so I must work around the problem. I want this list of <LineItem> nodes to deserialize into a List<LineItem> property and serialize flat like in the XML above.
As it turns out, the solution is remarkably simple. In the class definition simply decorate the List<LineItem> property with the [XmlElementAttribute] attribute and the XmlSerializer will handle flattenting out and inflating for you.
private List<LineItem> _LineItem;
[XmlElementAttribute]
public List<LineItem> LineItem
{
get { return _LineItem; }
set { _LineItem = value; }
}
So the code above is the only change to my class and it now serializes the generic list flat to XML and handles deserializing the list perfectly.
http://msdn.microsoft.com/en-us/library/2baksw0z(VS.80).aspx