Tired of writing XML Document and tags? and even more tired when you have to code exactly the reverse thing when reading back from XML document?
The solution is to make use of the XML Serialization in .NET!
This example shall give you an overall idea of the XML serialization function of .NET.
--> No more codes for XML Writing
--> No more codes for XML
--> 1000% higher productivity in writing codes
The codes sample is a prototype example for my company, which will be used as a file format eventually for data exchange.
Imports System.Xml.Serialization
Public Class PSF_XMLSerializer_PrototypeForm
Private Sub PSF_XMLSerializer_PrototypeForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim newPSF As New PortStatusFile
newPSF.FileVersion = "123"
newPSF.RevisionDate = "111"
newPSF.TS.Vessel_Code = "ABC"
newPSF.TS.Vessel_Oper = "XCL"
newPSF.CS.SMD.Add(New SMDetails("One"))
newPSF.CS.SMD.Add(New SMDetails("Two"))
newPSF.CS.SMD.Add(New SMDetails("Three"))
Dim xmlsel As New XmlSerializer(GetType(PortStatusFile))
Dim xmlWriter As New System.IO.StreamWriter("C:\test.txt")
xmlsel.Serialize(xmlWriter, newPSF)
xmlWriter.Close()
Dim xmlReader As New System.IO.StreamReader("C:\test.txt")
Dim anotherPSF As PortStatusFile = CType(xmlsel.Deserialize(xmlReader), PortStatusFile)
anotherPSF.RevisionDate = "9999"
anotherPSF.TS.Line = "SEA"
Dim xmlW2 As New System.IO.StreamWriter("C:\test2.txt")
xmlsel.Serialize(xmlW2, anotherPSF)
End Sub
End Class
<XmlRootAttribute("PSF", Namespace:="Seacon.eBiz", IsNullable:=False)> _
Public Class PortStatusFile
<XmlAttributeAttribute("version")> _
Public FileVersion As String
<XmlAttributeAttribute("Rev_Date")> _
Public RevisionDate As String
<XmlAttributeAttribute("SID")> _
Public SID As String
<XmlAttributeAttribute("format_datetime")> _
Private DateTimeFormat As String
Public TS As TerminalDetails
Public CS As CargoDetails
Public Sub New()
Me.TS = New TerminalDetails
Me.CS = New CargoDetails
End Sub
End Class
<XmlRoot("TDR", IsNullable:=False)> _
Public Class TerminalDetails
Public Vessel_Code As String
Public Vessel_Name As String
Public Vessel_Oper As String
Public Voyage As String
Public Leg As String
Public Line As String
Public Port_Code As String
End Class
<XmlRoot("SM", IsNullable:=False)> _
Public Class CargoDetails
'Multiple SMD
<XmlArrayItem(ElementName:="SMD_ITEM", _
IsNullable:=True, _
Type:=GetType(SMDetails)), _
XmlArray(ElementName:="SMD")> _
Public SMD As ArrayList
Public Sub New()
Me.SMD = New ArrayList
End Sub
End Class
<XmlRoot("SMD", IsNullable:=False)> _
Public Class SMDetails
Public Cntr_Num As String
Public Sub New()
End Sub
Public Sub New(ByVal cntrNum As String)
Me.Cntr_Num = cntrNum
End Sub
End Class
If you wanted to add stylesheet to your serialized object, check this out:
http://www.tkachenko.com/blog/archives/000246.html
No comments:
Post a Comment