Mar
17
Written by:
Steve Gray
3/17/2011 3:53 PM
In the last example we took a simple XML document and deserialized it into a class. This example takes that idea one step further. Our source XML document is a standard ‘order’ with an Order Header and Order Detail sections. The class that we’re going to send it into needs to have a Generic List (of Item) to hold the order details.
Also, in the last example each item in the class was decorated with an <XElement> directive. In this example we’ve remove those and placed a <Serializable> directive at the top of the class.
Also note that the <XmlAttribute> was applied to the OrderNumber property, and it got correctly picked up as an attribute in the XML document
Code Snippet
- Imports System.Xml.Serialization
- Imports Microsoft.VisualBasic
-
- Public Class Form2
-
- Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
- Try
- ' Declare an object variable of the type to be deserialized.
- Dim i As Order
-
- 'Create an instance of the XmlSerializer specifying type and namespace.
- 'the 'OrderedItem' class is below
- Dim serializer As New XmlSerializer(GetType(Order))
-
- 'open an XmlReader from a string
- 'the getXMLDoc function returns an XML document in string format
- Dim reader As System.Xml.XmlReader = System.Xml.XmlReader.Create(New System.IO.StringReader(getXMLDoc))
-
- ' Use the Deserialize method to restore the object's state.
- i = CType(serializer.Deserialize(reader), Order)
-
- ' Write out the properties of the object.
- Console.WriteLine("Item Name: " & i.OrderNumber)
- Console.WriteLine("Item Desc: " & i.CustomerNumber)
-
- Catch ex As Exception
- MsgBox(ex.Message)
- End Try
-
-
- End Sub
-
- Function getXMLDoc() As String
- Dim xElement As XElement
- xElement = <Order OrderNumber="ORD002">
- <CustomerNumber>CUST001</CustomerNumber>
- <Items>
- <Item>
- <ItemName>Widget</ItemName>
- <Quantity>1</Quantity>
- <UnitPrice>9</UnitPrice>
- </Item>
- <Item>
- <ItemName>Widget</ItemName>
- <Quantity>10</Quantity>
- <UnitPrice>2.3</UnitPrice>
- </Item>
- </Items>
- </Order>
-
- Return xElement.ToString
-
- End Function
- End Class
-
- 'This is the class that will be deserialized.
- <Serializable()> _
- Public Class Order
- <XmlAttribute()> _
- Public OrderNumber As String
-
- Public CustomerNumber As String
- Public Items As List(Of Item)
-
- End Class
-
- <Serializable()> _
- Public Class Item
- Public ItemName As String
- Public Quantity As Integer
- Public UnitPrice As Decimal
- End Class
As always, I welcome your comments!