|
'Module1.vb
Imports System.Xml.Serialization
Imports System.IO
Module Module1
Sub Main()
'How to serialize and deserialize an object to an XML file in Visual Basic .NET
'http://support.microsoft.com/kb/316730
'Set up product object or User Preferences object for that matter
Dim sFilename As String
Dim p As New clsProduct()
p.Name = "Widget"
p.Description = "Faster, better, cheaper"
p.Qty = 5
p.Username = "Dave"
p.HomeURL = "http://www.google.com"
sFilename = "c:\temp\" & p.Username & ".xml"
'Serialize object to a text file.
Dim objStreamWriter As New StreamWriter(sFilename)
Dim x As New XmlSerializer(p.GetType)
x.Serialize(objStreamWriter, p)
objStreamWriter.Close()
'Deserialize text file to a new object.
Dim objStreamReader As New StreamReader(sFilename)
Dim p2 As New clsProduct()
p2 = x.Deserialize(objStreamReader)
objStreamReader.Close()
'Display property values of the new product object.
Console.WriteLine(p2.Name)
Console.WriteLine(p2.Description)
Console.WriteLine(CStr(p2.Qty))
Console.WriteLine(p2.Username)
Console.WriteLine(p2.HomeURL)
Console.ReadLine()
End Sub
End Module
'clsProduct.vb
Public Class clsProduct
Private mstrName As String
Private mstrDescription As String
Private mintQty As Integer
Private mstrUsername As String
Private mstrHomeURL As String
Public Property Name() As String
Get
Name = mstrName
End Get
Set(ByVal Value As String)
mstrName = Value
End Set
End Property
Public Property Description() As String
Get
Description = mstrDescription
End Get
Set(ByVal Value As String)
mstrDescription = Value
End Set
End Property
_
Public Property Qty() As Integer
Get
Qty = mintQty
End Get
Set(ByVal Value As Integer)
mintQty = Value
End Set
End Property
Public Property Username() As String
Get
Username = mstrUsername
End Get
Set(ByVal Value As String)
mstrUsername = Value
End Set
End Property
Public Property HomeURL() As String
Get
HomeURL = mstrHomeURL
End Get
Set(ByVal Value As String)
mstrHomeURL = Value
End Set
End Property
End Class
|
|