How to Serialize One-to-Many
In .NET it is fairly easy to serialize some custom object (for example Order) to XML. Need just to use attributes provided by System.Xml.Serialization correctly:
- Serializable
- XmlElement
- XmlAttribute
However, it is less trivial to serialize a composite object, each instance of which may have an array of another custom object type as property (one-to-many relation). For example Order and OrderItem. Hint - use Type attribute and call the property - ArrayOf.... For example, Order can be defined like so:
[Serializable] public class Order { public Order() { } private int orderId; private DateTime orderDate = DateTime.MinValue; private OrderItem[] arrayOfOrderItem; [XmlElement(ElementName = "OrderId")] public int OrderId { get { return orderId; } set { orderId = value; } } [XmlElement(ElementName = "OrderDate")] public DateTime OrderDate { get { return orderDate; } set { orderDate = value; } } [XmlElement(ElementName = "ArrayOfOrderItem", Type = typeof(OrderItem[]))] public OrderItem[] ArrayOfOrderItem { get { return arrayOfOrderItem; } set { arrayOfOrderItem = value; } } }
OrderItem needs to be defined as Serializable also. Enjoy.
Monday, March 19, 2007 12:58 AM