Mar
17
Written by:
Steve Gray
3/17/2011 3:07 PM
I get to see quite a bit of XML, and my path in the past has always been to use LINQ to iterate through the document and read it into a class. Then I’d use the class to do whatever work I need to do.
This code takes advantage of the XmlSerializer.Deserialize method.
To run this code, create a Windows Forms application and drop this code into the form code behind. It is complete and should run unmodified.
Note that the OrderedItem class and the getXMLDoc function both make use of namespaces for two of the elements, so we show how to code this both with and without namespace references.
Code Snippet
- Imports System.Xml.Serialization
- Imports Microsoft.VisualBasic
-
- Public Class Form1
-
- Private Sub Form1_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 OrderedItem
-
- 'Create an instance of the XmlSerializer specifying type and namespace.
- 'the 'OrderedItem' class is below
- Dim serializer As New XmlSerializer(GetType(OrderedItem))
-
- '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), OrderedItem)
-
- ' Write out the properties of the object.
- Console.WriteLine("Item Name: " & i.ItemName)
- Console.WriteLine("Item Desc: " & i.Description)
-
- Catch ex As Exception
- MsgBox(ex.Message)
- End Try
-
-
- End Sub
-
- Function getXMLDoc() As String
- Dim xElement As XElement
- xElement = <OrderedItem xmlns:money="http://www.devshed.us">
- <ItemName>Widget</ItemName>
- <Description>Regular Widget</Description>
- <Quantity>10</Quantity>
- <money:UnitPrice>2.3</money:UnitPrice>
- <money:LineTotal>23</money:LineTotal>
- </OrderedItem>
-
- Return xElement.ToString
-
- End Function
- End Class
-
- ' This is the class that will be deserialized.
- Public Class OrderedItem
- <XmlElement()> _
- Public ItemName As String
-
- <XmlElement()> _
- Public Description As String
-
- <XmlElement()> _
- Public Quantity As Integer
-
- <XmlElement(Namespace:="http://www.devshed.us")> _
- Public UnitPrice As Decimal
-
- <XmlElement(Namespace:="http://www.devshed.us")> _
- Public LineTotal As Decimal
- ' A custom method used to calculate price per item.
- Public Sub Calculate()
- LineTotal = UnitPrice * Quantity
- End Sub
- End Class
As always, I welcome your comments!