将XML字符串反序列化为Object VB.NET

时间:2014-12-01 19:42:32

标签: xml vb.net serialization

我已经在网上看到了很多例子,但要么我无法理解应用程序,要么我的例子与我的转换太不同了。我有一个XML

<Interfaces>
    <Interface>
        <InterfaceCode>987</InterfaceCode>
        <AccessID>asdf</AccessID>
        <Password>654321</Password>
    </Interface>
    <Interface>
        <InterfaceCode>789</InterfaceCode>
        <AccessID>      </AccessID>
        <Password>      </Password>
    </Interface>
</Interfaces>

以下课程

<Serializable(), XmlRoot("Interfaces"), XmlType("Interfaces")>
Public Class InterfacesModel
    Property Interfaces As New List(Of InterfaceModel)
End Class

<Serializable(), XmlType("Interface")>
Public Class InterfaceModel
    Property InterfaceCode As String
    Property AccessID As String
    Property Password As String
End Class

以下代码生成InterfacesModel,其中包含空Interfaces列表:

Dim str As String = xmlString
Dim interfaces As InterfacesModel

Dim serializer As New XmlSerializer(GetType(InterfacesModel))
Using reader As TextReader = New StringReader(str)
     interfaces = serializer.Deserialize(reader)
End Using

我希望它将接口填充为List(InterfaceModel),这样我就可以在接口上为每个接口执行一个操作,并对每个接口执行一些操作。

2 个答案:

答案 0 :(得分:6)

您的财产需要XmlElement("Interface")。此外,您可以摆脱XmlType属性。我认为那些没有为你做任何事情。

<Serializable(), XmlRoot("Interfaces")>
Public Class InterfacesModel
    <XmlElement("Interface")> Property Interfaces As New List(Of InterfaceModel)
End Class

<Serializable()>
Public Class InterfaceModel
    Property InterfaceCode As String
    Property AccessID As String
    Property Password As String
End Class

答案 1 :(得分:0)

当我在编写可序列化的类时,我不使用标签,而只是使用类似的东西,并且效果相同

<Serializable>
Public Class Interfaces
    Public interface as InterfaceModel() 'The () Defines an array of InterFaceModels
End Class

<SerialzableAttribute>
Public Class InterfaceModel
    Public InterFaceCode As String
    Public AccessID As String
    Public Password As String
End Class