检查下面的代码,这lst
可能是您正在寻找的结构:
Dim xml As XElement = <additionalData>
<nameValuePair>
<name>amount</name>
<value>10</value>
</nameValuePair>
<nameValuePair>
<name>billerId</name>
<value>4665890107880063161</value>
</nameValuePair>
<nameValuePair>
<name>billNumber</name>
<value>12434829</value>
</nameValuePair>
</additionalData>
Dim lst As New List(Of KeyValuePair(Of String, String))
For Each nameValuePair As XElement In xml.Elements
Dim name As String = nameValuePair.<name>.Value
Dim value As String = nameValuePair.<value>.Value
lst.Add(New KeyValuePair(Of String, String)(name, value))
Next
您可以将 KeyValuePair 替换为您自己的另一个类,甚至可以将整个通用 List 替换为更复杂的东西。您使用 XML 文件的方式很可能保持不变。
这是lst
执行上述代码后的内容(调试器视图)。
编辑- 如果您定义一些自定义类:
Class AdditionalData : Inherits List(Of NameValuePair)
Sub New(xml As XElement)
For Each nameValuePair As XElement In xml.Elements
Dim name As String = nameValuePair.<name>.Value
Dim value As String = nameValuePair.<value>.Value
Me.Add(New NameValuePair(name, value))
Next
End Sub
End Class
Class NameValuePair
Public ReadOnly Name As String
Public ReadOnly Value As String
Sub New(name As String, value As String)
Me.Name = name
Me.Value = value
End Sub
End Class
您可以将上面的代码更改为:
Dim lst As New AdditionalData(xml) 'xml is inline XML file declared above
或者在您的情况下,它可能是:
Dim lst As New AdditionalData(XDocument.Load("path_to_xml").Root)
我故意让它接受 XElement,这样您可以传递内联 XML 或解析的 XML(来自流或其他)或从磁盘加载。additionalData
如果它是一个复杂的结构并且是其中的一部分,您甚至可以给它一个 XML 文件的子集。