Deserialize XML string to Object VB.NET

 ̄綄美尐妖づ 提交于 2021-01-27 15:12:36

问题


I've seen plenty of examples online but either I cannot make sense of the application or the example is too different from mine for me to transpose. I have a XML

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

And the following classes

<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

The following code produces a InterfacesModel with an empty Interfaces list:

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

I would expect it to populate Interfaces as a List(of InterfaceModel) so that I can perform a for each on Interfaces and do something to each Interface.


回答1:


You need XmlElement("Interface") on your property. Also, you can get rid of the XmlType attributes. I don't think those are doing anything for you.

<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



回答2:


When im writing serializable classes i dont use tags i just use something like this and it works the same

<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


来源:https://stackoverflow.com/questions/27235951/deserialize-xml-string-to-object-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!