序列化后,xml文件应该像这样,然后在vb.net中反序列化。我是编程的开端。任何帮助表示赞赏。
<?xml version="1.0"?>
<Countries>
<Country>
<CID>1</CID>
<CountryName>India</CountryName>
<States>
<State> New Delhi </State>
<State> Maharashtra </State>
<State> Rajasthan </State>
</States>
</Country>
<Country>
<CID>2</CID>
<CountryName>United States</CountryName>
<States>
<State> Washington </State>
<State> Texas </State>
</States>
</Country>
<Country>
<CID>3</CID>
<CountryName>Australia</CountryName>
<States>
<State> Queensland </State>
<State> Victoria </State>
</States>
</Country>
</Countries>
我建议您一定要研究XML序列化。在MSDN上可以找到很多信息(但也可以使用任何搜索引擎)。例如在MSDN上:XML序列化介绍。
如果还没有,请输入代码。我将使反序列化给定的XML结构非常简单。您可以为国家/地区创建简单的类定义,如下所示:
Public Class Country
Public Property CID As Integer
Public Property CountryName As String
Public Property States As List(Of String)
Public Sub New()
States = New List(Of String)()
End Sub
End Class
现在这还行不通100%。您必须通过状态列表帮助序列化对象。您可以注释(带有属性)States
,因此序列化程序知道每个项目的名称都不同(默认名称为<string>item</string>
)。您可以为此使用XmlArrayItem
属性。
<Serializable()>
Public Class Country
Public Property CID As Integer
Public Property CountryName As String
<XmlArrayItem("State")>
Public Property States As List(Of String)
Public Sub New()
States = New List(Of String)()
End Sub
End Class
最后,进行反序列化。我会反序列化为List(Of Country)
,因为它显然是一个列表。(假设以上XML存储在文件“ obj.xml”中。)
Dim serializer As New XmlSerializer(GetType(List(Of Country)))
Dim deserialized As List(Of Country) = Nothing
Using file = System.IO.File.OpenRead("obj.xml")
deserialized = DirectCast(serializer.Deserialize(file), List(Of Country))
End Using
现在,我们仍然需要帮助序列化程序对象,因为否则它不知道如何反序列化给定的XML。因为它不能正确确定根节点。我们可以在此处使用构造函数的重载,在其中可以说出根节点是(XmlSerializer Constructor (Type, XmlRootAttribute)
)。
反序列化的最终代码为:
Dim serializer As New XmlSerializer(GetType(List(Of Country)), New XmlRootAttribute("Countries"))
Dim deserialized As List(Of Country) = Nothing
Using file = System.IO.File.OpenRead("obj.xml")
deserialized = DirectCast(serializer.Deserialize(file), List(Of Country))
End Using
序列化代码(写入文件“ obj.xml”):
Dim countries As New List(Of Country)()
' Make sure you add the countries to the list
Dim serializer As New XmlSerializer(GetType(List(Of Country)), New XmlRootAttribute("Countries"))
Using file As System.IO.FileStream = System.IO.File.Open("obj.xml", IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
serializer.Serialize(file, countries)
End Using
通过搜索和阅读文档,可以很容易地找到所有这些。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句