我要讀XML文檔數據,是在這裏:閱讀的XMLDocument具有相同的元素名稱
<root>
<cartype>Mercedes</cartype>
<production>2005</production>
<fuel>Diesel</fuel>
<color>Red</color>
<services>
<service>
<year>2006</year>
<km>47800</km>
<city>Stuttgart</city>
</service>
<service>
<year>2007</year>
<km>92125</km>
<city>FFM</city>
</service>
<service>
<km>180420</km>
<year>2009</year>
<city>Hannover</city>
</service>
</services>
<condition>Good</condition>
</root>
然後我讀它是這樣:
Dim cartype As String
Dim fuel As String
Dim production As String
Dim color As String
Dim serviceyear() As String = {"", "", ""}
Dim servicekm() As String = {"", "", ""}
Dim sevicecity() As String = {"", "", ""}
Dim doc As XmlDocument = New XmlDocument()
doc.Load("mercedes.xml")
Dim root As XmlElement = doc.DocumentElement
Dim node As XmlNode = root.SelectSingleNode("production")
If Not node Is Nothing Then production = node.InnerText
node = root.SelectSingleNode("cartype")
If Not node Is Nothing Then cartype = node.InnerText
node = root.SelectSingleNode("fuel")
If Not node Is Nothing Then fuel = node.InnerText
node = root.SelectSingleNode("color")
If Not node Is Nothing Then color = node.InnerText
node = root.SelectSingleNode("services/service/year") '' first service year
If Not node Is Nothing Then serviceyear(0) = node.InnerText
node = root.SelectSingleNode("services/service/year") '' second service year
If Not node Is Nothing Then serviceyear(1) = node.InnerText
具有獨特的元素名稱讀節點是確定的,但我不知道如何讀取數組中的所有「服務」,因爲顯示的代碼只讀取第一個服務。服務可能從0到未定義的數字。函數必須儘可能快,因爲大量的xml必須在可能的時間內被減少。
謝謝你馬克非常教育答案和可行的,方便的解決方案。我更喜歡oldfashion的方式,它很好。只需要改變這一行:「對於每個服務作爲XmlNode在服務中」可能是因爲Option Strict開啓。 – 2014-11-14 19:23:51
很高興有用。對於'作爲XmlNode'部分,我總是有'Option Infer On'和'Option Strict On',以避免在嚴格打字的同時輕輕打字,所以我總是忘記在例子中明確表達 - 對此深表歉意。 – Mark 2014-11-14 19:34:09