2012-10-16 55 views
1

由于有多个列表的事实,我无法反序列化此表,我知道我需要一个列表,因为他们重复我的trs,但也为我的tds,因为他们也重复,尝试读取tds的值时出现问题,因为我以列表格式存在。如何反序列化具有多个列表的表

这里是我的xml:

<table> 
<tr> 
    <td>1</td> 
    <td>2</td> 
</tr> 
<tr> 
    <td>3</td> 
    <td>4</td> 
</tr> 
</table> 

而且我的课:

Public Class table 
    Private newtr As List(Of tr) 
    <XmlElement()> _ 
    Public Property tr() As List(Of tr) 
     Get 
      Return newtr 
     End Get 
     Set(ByVal value As List(Of tr)) 
      newtr = value 
     End Set 
    End Property 
End Class 


Public Class tr 
    Private newtd As List(Of td) 
    <XmlElement()> _ 
    Public Property td() As List(Of td) 
     Get 
      Return newtd 
     End Get 
     Set(ByVal value As List(Of td)) 
      newtd = value 
     End Set 
    End Property 
End Class 


Public Class td 
    Private newvalue As String 
    <XmlElement()> _ 
    Public Property td() As String 
     Get 
      Return newvalue 
     End Get 
     Set(ByVal value As String) 
      newvalue = value 
     End Set 
    End Property 
End Class 

而且我的代码:

Public Sub test2() 
    Dim rr As New table() 
    Dim xx As New XmlSerializer(rr.GetType) 
    Dim objStreamReader2 As New StreamReader("table.xml") 
    Dim rr2 As New table() 
    rr2 = xx.Deserialize(objStreamReader2) 
    For Each ii As tr In rr2.tr 
     MsgBox(ii.td) 
    Next 
End Sub 

因此,任何关于我如何能得到的值中的每一个想法在tds里面?谢谢!

回答

1

您目前有声明为列表tr.td,所以你不能只是输出它作为一个字符串。你会需要遍历每个td项目列表:

For Each currTr As tr In rr2.tr 
    For Each currTd As td In currTr.td 
     MessageBox.Show(currTd.td) 
    Next 
Next 

然而,这不会在您的示例XML正确读取值。在你的例子中,每个td元素包含一个字符串,而不是另一个同名的子元素。但是你的数据结构假设XML的结构是这样的:

<table> 
<tr> 
    <td> 
    <td>1</td> 
    </td> 
    <td> 
    <td>2</td> 
    </td> 
</tr> 
<tr> 
    <td> 
    <td>3</td> 
    </td> 
    <td> 
    <td>4</td> 
    </td> 
</tr> 
</table> 

为了解决这个问题,你只需要两个类是这样的:

Public Class table 
    Private newtr As List(Of tr) 
    <XmlElement()> _ 
    Public Property tr() As List(Of tr) 
     Get 
      Return newtr 
     End Get 
     Set(ByVal value As List(Of tr)) 
      newtr = value 
     End Set 
    End Property 
End Class 


Public Class tr 
    Private newtd As List(Of String) 
    <XmlElement()> _ 
    Public Property td() As List(Of String) 
     Get 
      Return newtd 
     End Get 
     Set(ByVal value As List(Of String)) 
      newtd = value 
     End Set 
    End Property 
End Class 

然后,你就可以通过反序列化对象循环像这样:

For Each currTr As tr In rr2.tr 
    For Each currTd As String In currTr.td 
     MessageBox.Show(currTd) 
    Next 
Next 
+1

如果它不是史蒂文了。 :) – user1676874

+0

啊!这是你:)我没有认出你的数值。我需要更新我的照片。恐怕这有点太令人不安。 –

+1

我应该解决这个问题,你看起来像一个程序员,没有错。 :) – user1676874

相关问题