问题
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