VB.Net Tutorial/XML/XmlSerializer — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 12:54, 26 мая 2010
DeSerialize from xml file
Imports System.Xml.Serialization, System.IO
Public Class Tester
Public Shared Sub Main
Dim theSerializer As New XmlSerializer(GetType(employee))
Dim sw As New StreamReader("data.xml")
Dim theWorker As employee
theWorker = theSerializer.Deserialize(sw)
Console.WriteLine(theWorker.first_name )
Console.WriteLine(theWorker.last_name )
Console.WriteLine(theWorker.title)
End Sub
End Class
Public Class employee
Public first_name As String
Public last_name As String
Public title As String
Public Sub New()
End Sub
Public Sub New(ByVal first_name As String,ByVal last_name As String,ByVal title As String)
Me.first_name = first_name
Me.last_name = last_name
Me.title = title
End Sub
End Class
Serialize Class to xml file
Imports System.Xml.Serialization, System.IO
Public Class Tester
Public Shared Sub Main
Dim theSerializer As New XmlSerializer(GetType(employee))
Dim SGamgee As New employee("A", "G", "C")
Dim sw As New StreamWriter("data.xml")
theSerializer.Serialize(sw, SGamgee)
End Sub
End Class
Public Class employee
Public first_name As String
Public last_name As String
Public title As String
Public Sub New()
End Sub
Public Sub New(ByVal first_name As String,ByVal last_name As String,ByVal title As String)
Me.first_name = first_name
Me.last_name = last_name
Me.title = title
End Sub
End Class
XML Serialization
Imports System.IO
Imports System.Xml.Serialization
Public Class Point
Public X As Integer
Public Y As Integer
Public Overrides Function ToString() As String
Return "(" & X & "," & Y & ")"
End Function
End Class
Module Test
Sub Main()
Dim P1 As New Point()
P1.X = 6
P1.Y = 4
SaveToFile(P1)
Dim P2 As Point = RetrieveFromFile()
Console.WriteLine(P2.ToString())
End Sub
Sub SaveToFile(P as Point)
Dim Serializer As New XmlSerializer(GetType(Point))
Dim Writer As StreamWriter = New StreamWriter("point.xml")
Serializer.Serialize(Writer, P)
Writer.Close()
End Sub
Function RetrieveFromFile() As Point
Dim ReturnObject As Point
Dim Serializer As New XmlSerializer(GetType(Point))
Dim FS As FileStream = New FileStream("point.xml", FileMode.Open)
ReturnObject = CType(Serializer.Deserialize(FS), Point)
FS.Close()
Return ReturnObject
End Function
End Module
(6,4)