我有一个BOOKING类,它继承了一个列表(Message) 我想知道如何序列化这个。 我的BOOKING类包含Message的属性和3个属性,称为partner,transaction和version,
我的Message类有很多属性可以创建预订,
现在当我要序列化时,我使用这个
Dim z As New BOOKING
Dim x As New Message
z.partner = "company name"
z.transaction = "BOOKING"
z.version = "1.0"
x.MessageType = "C"
x.CustomerNumber = "123"
x.BookingReference = "5845"
x.CustomerBookingReference = "036598"
x.OutwardRoute = "PEMROS"
x.SailingDate = "20120107"
z.Message = x
SaveAsXML(z)
使用下面的另存为xmlfunction代码
Public Shared Function SaveAsXML(ByRef val As BOOKING)
Try
Dim objStreamWriter As New StreamWriter("c:\ftptest\New Booking\" + val.FileName)
Dim y As New XmlSerializer(val.GetType)
y.Serialize(objStreamWriter, val)
objStreamWriter.Close()
Return True
Catch ex As Exception
Throw ex
End Try
End Function
我知道哪里出错了?
我的BOOKING课程如下
Public Class BOOKING : Inherits List(Of Message)
Private Property MessageProperty As Message
<XmlAttribute>
Public Property partner As String
<XmlAttribute>
Public Property transaction As String
<XmlAttribute>
Public Property version As String
Public Property Message As Message
Get
Return MessageProperty
End Get
Set(value As Message)
MessageProperty = value
End Set
End Property
这里也是上面代码创建的xml。
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMessage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
这是我的反序列化代码
Try
Dim Samples As BOOKING
Using objStreamReader As New StreamReader(filepath) 'Path where file is
Dim x As New XmlSerializer(GetType(BOOKING), New XmlRootAttribute("BOOKING"))
Samples = x.Deserialize(objStreamReader)
End Using
Form1.DataGridView1.DataSource = Samples
Return True
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
答案 0 :(得分:0)
您的类结构使序列化程序混乱。如果Booking
继承自List(Of Message),那么它的Message
属性类型Message
也是没有意义的(因为 已经是消息类型)。它成为一个自我参考。我做了一些其他问题和调整,并且序列化很好:
Public Class BOOKING
Public Property partner As String
Public Property transaction As String
Public Property version As String
Public Property XMsgs As New List(Of XMessage)
End Class
Public Class XMessage
Public Property A As String
Public Property C As String
Public Property B As String
End Class
a)Public Property Message As Message
在VB中建议给出与该类型相同的属性。因此我使用了XMessage
b)你没有正确使用XMLAttribute。应该有几个IDE错误,XML序列化不需要它
c)为了每个数据包处理多个消息,我将XMsgs更改为List属性。这允许一个BOOKING数据集用于许多消息。如果您想要每次预订1个消息,则不需要2个课程,只需将其设为列表(预订)即可。
d)摆脱用作支持领域的私有财产。
测试和序列化代码:
Dim B As New BOOKING
B.partner = "abcdef"
B.transaction = "12345"
B.version = "1.00.1"
Dim m As New XMessage
m.A = "foo"
m.B = "bar"
B.XMsgs.Add(m) ' use List prop as a List
' Using block to dispose of streamwriter
Using sr As New System.IO.StreamWriter("c:\Temp\Booking.xml")
Dim y As New Serialization.XmlSerializer(B.GetType)
y.Serialize(sr, B)
End Using