我有一个xml文件
<config>
<email Host="201.175.0.0" From="address@gmail.com" 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
这是正确的,什么是更好的方法?
答案 0 :(得分: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中的Dictionary)来存储这些属性,而不是使用一堆变量。
在这种情况下,它看起来像这样:
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)