gpt4 book ai didi

xml - 尝试使用 VB.net 序列化和反序列化 xml 文件

转载 作者:数据小太阳 更新时间:2023-10-29 02:53:28 25 4
gpt4 key购买 nike

序列化后的 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 上:Introducing XML Serialization .

如果您还没有,请获取代码。我会让反序列化给定的 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 attribute为此。

<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

所有这些都可以通过搜索和阅读文档很容易地找到。

关于xml - 尝试使用 VB.net 序列化和反序列化 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24246002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com