2014-06-16 67 views
1

我序列化後,xml文件應該這樣,然後我想在vb.net中反序列化這個。我是編程的一名成員。任何幫助表示讚賞。試圖使用VB.net序列化和反序列化一個XML文件

<?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> 
+0

你應該從這裏開始http://msdn.microsoft.com/library/58a18dwa(v=vs.90).aspx?cs-save-lang=1&cs-lang=vb – Ksv3n

+0

是保存一些數據和目的重新加載或將數據導出到給定的文件佈局? – Plutonix

+0

您是否有需要像這樣序列化的數據結構?請分享一些VB.NET代碼。你需要序列化並反序列化這個XML嗎? – Neolisk

回答

6

我建議你一定要看看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 

這一切可能已經發現很容易通過搜索和閱讀文檔。