2012-04-08 35 views
0

我有一個非常複雜的XML提取特定值超出XML

,我需要從

selectSingleNode(@"/TimeInTransitResponse/TransitResponse/ServiceSummary/EstimatedArrival/BusinessTransitDays").InnerText) 

單值,但大約有7項與此位置,因此只返回第一個我需要最後一個。

回答

0

使用SelectNodes代替:

Dim nodeList As XmlNodeList = root.SelectNodes(@"/TimeInTransitResponse/TransitResponse/ServiceSummary/EstimatedArrival/BusinessTransitDays") 
Dim lastNode As XmlNode = nodeList.Item(nodeList.Count - 1) 
Dim lastNodeValue As Decimal = Convert.ToDecimal(lastNode.InnerText) 

然後採取在列表中的最後一個節點。

+0

我如何確保它始終是我需要的節點的最後一個節點總是在響應中,並且將永遠是最後的,但我永遠不知道我是否會收到1,2,3,4,5,6或7個條目。 – 2012-04-08 02:03:35

+0

nodeList將有一個Count,只需要使用count-1。我會更新我的答案。 – mgnoonan 2012-04-08 02:08:28

+0

以及如何將最後一個節點轉換爲小數? – 2012-04-08 02:25:31

2

您可以使用索引和索引裏面你可以把最後一個()函數 - 是這樣的:

"/TimeInTransitResponse/TransitResponse/ServiceSummary/EstimatedArrival/BusinessTransitDays[last()]" 

last XPath函數在MSDN。

+0

謝謝您的答覆,但它根本不VS誤差與工作「錯誤名稱‘最後’不在當前情況下存在」 – 2012-04-08 02:05:38

+0

固定XPath和交鋒鏈接到MSDN(slighgly更容易比閱讀原來的W3C之一 - http://www.w3.org/TR/xpath/) – 2012-04-08 02:42:38

+0

不知道你爲什麼得到錯誤。括號的意圖是獲得最後一個元素,而不是第一個EstimatedArrival的最後一個元素。考慮下面這個例子: xmlDocument.LoadXml( 「」 + 「」 + 「 ABC」 + 「」 + 「」 + 「 XYZ」 + 「」 + 「「); Console.WriteLine(xmlDocument.SelectSingleNode(「/ root/element/child [last()]」)); (xmlDocument.SelectSingleNode(「(/ root/element/child)[last()]」)); 第一個會輸出「abc」,而第二個「xyz」 – Pawel 2012-04-08 03:02:15