Introduction
System.Xml.Serialization
provides methods for converting objects, including those based on custom classes, to and from XML files. With XML serialization, you can write almost any object to a text file for later retrieval with only a few lines of code. Similarly, you can use XML serialization to transmit objects between computers through Web services-even if the remote computer is not using the .NET Framework.
Background
This example shows the simple way of using XML Serialization. With this concept, anyone can set the value to a specific object and store the object as an XML file to any location and retrieve the same file by other/same user at any time.
Using the Code
How to Use XML to Serialize an Object
Dim xs As XmlSerializer = New XmlSerializer(GetType(Order))
Dim sw As StreamWriter
sw = New StreamWriter(Application.StartupPath & "\Order\Order.xml")
Dim p_ord As New Order
Try
p_ord.Customer = txtcustomer.Text
p_ord.TableNo = txttableno.Text
p_ord.MenuItem = txtmenuitem.Text
p_ord.OrderedQty = txtqty.Text
p_ord.OrderedTaste = cmbTaste.SelectedItem.ToString
p_ord.OrderedFat = cmbFat.SelectedItem.ToString
xs.Serialize(sw, p_ord)
sw.Close()
MsgBox("Order has been placed successfully.")
TabControl1.SelectedTab = TabControl1.TabPages(1)
Catch ex As Exception
MsgBox(ex.ToString)
Finally
p_ord = Nothing
End Try
How to Use XML to Deserialize an Object
Dim r_ord As Order
Dim sr As StreamReader
Dim xs As XmlSerializer = New XmlSerializer(GetType(Order))
Try
sr = New StreamReader(Application.StartupPath & "\Order\Order.xml")
r_ord = xs.Deserialize(sr)
sr.Close()
lblcustomer.Text = r_ord.Customer
lbltableno.Text = r_ord.TableNo
lblMenuitem.Text = r_ord.MenuItem
lblqty.Text = r_ord.OrderedQty
lblTaste.Text = r_ord.OrderedTaste
lblFats.Text = r_ord.OrderedFat
Catch ex As Exception
MsgBox(ex.ToString)
Finally
r_ord = Nothing
End Try
Output XML File
="1.0"="utf-8"
<Class_Order xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Customer>Bruce Preece</Customer>
<TableNo>4</TableNo>
<OrderedQty>3</OrderedQty>
<OrderedTaste>None</OrderedTaste>
<OrderedFat>None</OrderedFat>
<MenuItem>Veg Cheese Burger</MenuItem>
</Class_Order>
Points of Interest
XML serialization cannot be used to serialize private data or object graphs. To serialize an object, first create a stream
, TextWriter
, or XmlWriter
. Then create an XmlSerializer
object and call the XmlSerializer.Serialize
method. To deserialize an object, follow the same steps but call the XmlSerializer.Deserialize
method.
Updates
Visit XML Serialization Part-2.
This article helps you brush up the advanced concepts of XML Serialization and abstract
class as well.