2012-12-05 72 views
0

我有一個XML文件讀取XML和屬性分配給變量在vb.net

<config> 
    <email Host="201.175.0.0" From="[email protected]" Pass="xxx" Name="NameT"/> 
    <combo/> 
    <list sex="female"/> 
</config> 

我如何分配的屬性來在vb.net變量的值?

我是做

Dim doc As XmlDocument = New XmlDocument() 
doc.Load("Test.xml") 
Dim Host = doc.DocumentElement.Attributes.ItemOf("Host").InnerText 
Dim From = doc.DocumentElement.Attributes.ItemOf("From").InnerText 
Dim Pass = doc.DocumentElement.Attributes.ItemOf("Pass").InnerText 
Dim Name = doc.DocumentElement.Attributes.ItemOf("Name").InnerText 

這是正確的,這將是一個更好的辦法?

回答

1

試試這個,而是:

Dim doc As XmlDocument = New XmlDocument() 
doc.Load("Test.xml") 
Dim root As XmlNode = doc.DocumentElement 
Dim nodeEmail As XmlNode = root.SelectSingleNode("/config/email") 
Dim Host As String = nodeEmail.Attributes.ItemOf("Host").InnerText 
Dim From As String = nodeEmail.Attributes.ItemOf("From").InnerText 
Dim Pass As String = nodeEmail.Attributes.ItemOf("Pass").InnerText 
Dim Name As String = nodeEmail.Attributes.ItemOf("Name").InnerText 

您可能還需要考慮使用關聯數組(詞典中的VB)來存放這些屬性,而不是使用一組變量。

在這種情況下,它應該是這樣的:

Dim doc As XmlDocument = New XmlDocument() 
doc.Load("Test.xml") 
Dim root As XmlNode = doc.DocumentElement 
Dim nodeEmail As XmlNode = root.SelectSingleNode("/config/email") 
Dim dictionary As New Dictionary(Of String, String) 
dictionary.Add("Host", nodeEmail.Attributes.ItemOf("Host").InnerText) 
dictionary.Add("From", nodeEmail.Attributes.ItemOf("From").InnerText) 
dictionary.Add("Pass", nodeEmail.Attributes.ItemOf("Pass").InnerText) 
dictionary.Add("name", nodeEmail.Attributes.ItemOf("Name").InnerText) 
+0

那是一個很不錯的主意,你必須使用字典的例子嗎? – cMinor