Tuesday, March 24, 2009

Mapping an XML to Business Objects using LINQ

Class Customer

Private _iD As Integer
Public Property ID() As Boolean
Get
Return _iD
End Get
Set(ByVal Value As Boolean)
_iD = Value
End Set
End Property

Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal Value As String)
_name = Value
End Set
End Property

Private _department As String
Public Property Department() As String
Get
Return _department
End Get
Set(ByVal Value As String)
_department = Value
End Set
End Property

Private _orderList As New List(Of Order)
Public Property OrderList() As List(Of Order)
Get
Me.LoadOrders()
Return Me._orderList
End Get

Set(ByVal value As List(Of Order))
Me._orderList = value
End Set
End Property

Private Sub LoadOrders()

End Sub
End Class


Class Order
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal Value As String)
_name = Value
End Set
End Property

Private _quantity As String
Public Property Quantity() As String
Get
Return _quantity
End Get
Set(ByVal Value As String)
_quantity = Value
End Set
End Property

End Class

Module Module1

Sub Main()

Const documentPath As String = "D:\Others\My Tools\Sample Projects\TestVBConsole\TestVBConsole\Customer.xml"

Dim document As XDocument = LoadDocument(documentPath)

Dim customer = From cust In document.Elements("Customer") _
Select New Customer _
With { _
.ID = cust.Element("ID").Value _
, .Name = cust.Element("Name").Value _
, .Department = cust.Element("Department").Value _
, .OrderList = (From order In cust.Elements("OrderList").Elements("Order") _
Select New Order() With { _
.Name = order.Element("ItemId").Value, _
.Quantity = order.Element("Quantity").Value}).ToList() _
}

Dim moreQuantityOrders = From cust In customer _
From orderList In cust.OrderList _
Where (orderList.Quantity > 1)

Console.ReadLine()
End Sub

Private Function LoadDocument(ByVal documentPath As String) As XDocument

Dim document = XDocument.Load(documentPath)
Return document

End Function

End Module

No comments:

Post a Comment