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

sub*_*ndu 2 xml vb.net serialization

我序列化之后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>
Run Code Online (Sandbox Code Playgroud)

Sty*_*xxy 6

我建议你一定要研究XML序列化.可以在MSDN上找到很多信息(但也可以使用任何搜索引擎).例如,在MSDN上:介绍XML序列化.

如果你还没有,代码.我会非常简单地反序列化给定的XML结构.您可以为Country创建一个简单的类定义,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

现在这还不行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
Run Code Online (Sandbox Code Playgroud)

最后,用于反序列化.我将反序列化为a 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
Run Code Online (Sandbox Code Playgroud)

现在我们仍然需要帮助序列化程序对象,因为否则它不知道如何反序列化给定的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
Run Code Online (Sandbox Code Playgroud)

序列化代码(写入文件"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
Run Code Online (Sandbox Code Playgroud)

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