自定义类层次结构,用于使用具有未知数量(名称,值)元素的XML

时间:2013-09-22 08:47:35

标签: vb.net xml-parsing

我试图在另一个结构中定义一个结构数组,但遇到了挑战。 基本上我应该使用xml节点,如下所示:

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

我需要将nameValuePair定义为父结构中名为additionalData

的结构数组

2 个答案:

答案 0 :(得分:1)

包含KeyValue-Pairs的数据结构是Dictionary。如果您不需要特定订单,可以使用它

Dim additionalData As New Dictionary(Of String, String)()
additionalData.Add("myname", "myvalue")

如果您的商品按特定顺序排列,则可以使用List

Dim additionalData As New List(Of KeyValuePair(Of String, String))()

Dim additionalDataItem As New KeyValuePair(Of String, String)("myname", "myvalue")
additionalData.Add(additionalDataItem)

修改

   struct Transaction
   {
      public Dictionary<string, string> additionalData;
   }

Transaction transaction;
transaction.additionalData = new Dictionary<string, string>();

transaction.additionalData.Add("amount", "10");

答案 1 :(得分:0)

检查以下代码,此处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的内容。

enter image description here

编辑 - 如果您定义了一些自定义类:

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(来自流或其他方式)或从磁盘加载。你甚至可以给它一个XML文件的子集,如果它是一个复杂的结构并且additionalData是它的一部分。