我正在尝试反序列化一个看起来像这个
的简单xml<categories>
<category name="camera">
<tags>
<tag name="6" value="stdy_cam"/>
<tag name="7" value="shaky"/>
</tags>
</category>
<category name="classify">
<tags></tags>
</category>
</categories>
这是我的加载方法 -
Private Sub loadAllCategories()
Dim serializer As XmlSerializer
Using stream As New System.IO.FileStream("C:\temp\tags2.xml", IO.FileMode.Open)
serializer = New XmlSerializer(GetType(List(Of Category)), New XmlRootAttribute("categories"))
Me.Categories = DirectCast(serializer.Deserialize(stream), List(Of Category))
End Using
End Sub
这些是我的课程 -
<Serializable()>
Public Class Category
<XmlAttribute("name")>
Public Property Name As String
<XmlArrayItem("tag")>
Public Property Tags As New List(Of Tag)
End Class
<Serializable()>
Public Class Tag
<XmlAttribute("name")>
Public Property Name As String
<XmlAttribute("value")>
Public Property Value As String
End Class
一切似乎都没问题,但是当我运行程序时,类别列表总是空的。该程序不会抛出任何错误或异常。当我调试时,它只显示0作为类别的计数。我可能做错了什么?
答案 0 :(得分:3)
您在列表中获得零,因为您的班级名为Category
且您的元素为category
,小写 c 。试试这个:
<XmlType(TypeName:="category")>
Public Class Category
<XmlAttribute("name")>
Public Property Name As String
<XmlArrayItem("tag")>
Public Property Tags As New List(Of Tag)
End Class
您也可以删除serializable属性。
修改修正了标签:
<XmlType(TypeName:="category")>
Public Class Category
<XmlAttribute("name")>
Public Property Name As String
<XmlArray("tags")>
Public Property Tags As New List(Of Tag)
End Class
<XmlType(TypeName:="tag")>
Public Class Tag
<XmlAttribute("name")>
Public Property Name As String
<XmlAttribute("value")>
Public Property Value As String
End Class