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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27235951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:32:04  来源:igfitidea点击:

Deserialize XML string to Object VB.NET

xmlvb.netserialization

提问by theB3RV

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

我在网上看过很多例子,但要么我看不懂应用程序,要么这个例子与我的太不同,我无法转置。我有一个 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 InterfacesModelwith an empty Interfaceslist:

以下代码生成一个InterfacesModelInterfaces列表:

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.

我希望它将接口填充为列表(InterfaceModel),以便我可以为每个接口执行一个操作并对每个接口执行一些操作。

回答by Uber Schnoz

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.

你需要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

回答by LordComfy

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