2013-06-24 85 views
3

我在處理XMl文件時遇到問題。我想循環(使用VB.NET)該文件並提取OrderID元素的所有值。使用VB.NET循環瀏覽XML文件

<?xml version="1.0"?> 
<ListOrdersResponse xmlns="https://xxx.xxxxxx.com/Orders/999uuu777"> 
    <ListOrdersResult> 
    <NextToken>XXXXXXXXXX</NextToken> 
    <Orders> 
     <Order> 
     <ShipmentServiceLevelCategory>Standard</ShipmentServiceLevelCategory> 
     <OrderId>ooooooooo</OrderId> 
     </Order> 
     <Order> 
     <ShipmentServiceLevelCategory>Standard</ShipmentServiceLevelCategory> 
     <OrderId>ujuujujuj</OrderId> 
     </Order> 
     </Orders> 
    <CreatedBefore>2013-06-19T09:10:47Z</CreatedBefore> 
    </ListOrdersResult> 
    <ResponseMetadata> 
    <RequestId>8e34f7d9-3af7-4490-801b-cccc7777yu</RequestId> 
    </ResponseMetadata> 
</ListOrdersResponse> 

這裏是我嘗試代碼,但它通過任何幫助將衷心感謝每個訂單

Dim doc As New XmlDocument() 
doc.Load(file) 
Dim nodelist As XmlNodeList = doc.SelectNodes(".//Orders/Order") 
For Each node As XmlElement In nodelist 
    console.writeline(node.SelectSingleNode("OrderID").InnerText) 
Next 

不循環。

回答

5

試試這個:

doc.Load(file) 
nodelist = doc.GetElementsByTagName("Order") 

For Each node As XmlElement In nodelist 
    Console.Writeline(node("OrderID").InnerText) 
Next 
0

XPath表達式我運行得到兩個訂單是//tns:Order

Dim doc As New XmlDocument() 
doc.Load(file) 
Dim nodelist As XmlNodeList = doc.SelectNodes("//tns:Order") 
For Each node As XmlElement In nodelist 
    '2 exist 
Next 
+0

感謝您的答覆。如果用「// tns:Order」取代「.//Orders/Order」,我會得到一個異常。你能解釋一下// tns:路徑是什麼嗎? – user2516387

+0

很抱歉忘了附上例外。它是需要的命名空間管理器或XsltContext。該查詢具有前綴,變量或用戶定義的函數。 – user2516387

+0

@ user2516387 - 'tns'只是DonA在創建示例程序時使用的xml名稱空間別名。你可以刪除它。 – JDB