本文介绍了将 XML 字符串反序列化为对象 VB.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上看到了很多示例,但要么我无法理解该应用程序,要么示例与我的太不同,我无法转置.我有一个 XML

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>

以及以下课程

<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 列表:

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

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

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.

推荐答案

您的资产需要 XmlElement("Interface").此外,您可以摆脱 XmlType 属性.我不认为那些人在为你做任何事情.

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

这篇关于将 XML 字符串反序列化为对象 VB.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 18:24