2012-06-01 23 views
1

我想從web服務獲取數據,只返回一個結果,庫存中給定項目的數量。如何從Soap Web Response獲取元素數據? VB.NET

我成功地得到一個結果,但需要從中去除所有的XML代碼,以簡單的返回數量,返回的XML看起來像:

<?xml version="1.0" encoding="utf-8"?> 
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> 
    <soap:Body> 
    <stockenquiryResponse xmlns="https://webservices.electrovision.co.uk"> 
     <stockenquiryResult>**THE NUMBER I NEED**</stockenquiryResult> 
    </stockenquiryResponse> 
    </soap:Body> 
</soap:Envelope> 

我敢肯定,這已經被問很多次,但我找不到一個簡單的解決方案,只需從stockenquiryresult標籤中獲取價值。

get value from XML in vbnet

似乎是一個正確的答案,但我不能得到它的工作。

http://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.80).aspx

正確地只是一對夫婦的調整來獲取數據,最顯着的改變內容類型application/soap+xml並傳遞:

如果有幫助,我從獲得使用示例數據數據爲XML。

我在ASP.NET 2.0中使用VB。

回答

3

有一些內置的.NET類可以用來讀取XML。

使用XmlDocument的

XmlDocument的暴露你的DOM(文檔對象模型)的Web服務中檢索XML字符串。你可以閱讀關於MSDN的XmlDocument。

Dim XMLDoc as new XMLDocument 

XMLDoc.LoadXML(XMLString) 

Dim Result as string = XMLDoc.LastChild.InnerText 

'Alternatively, you can use SelectSingleNode. 
'You will need to determine the correct XPath expression. 
'Dim Result as string = XMLDoc.SelectSingleNode("XPathToNode").InnerText 

如果您選擇使用的SelectSingleNode,該XPath documentation on MSDN會派上用場。

使用的XmlReader

對於快如讀取一個標籤的東西,你也可以使用一個XmlReader(MSDN Documentation)。不像XmlDocument的,XMLReader不能暴露XML作爲DOM。的XmlReader是一個只進閱讀器,但應該比XmlDocument更快,更輕量,這對你的情況很好,

Dim XSettings as new XmlReaderSettings 
'You can use XSettings to set specific settings on the XmlReader below. 
'See linked docs. 

Using SReader as New StringReader(XMLString) 

    Dim X as XmlReader = XmlReader.Create(SReader, XSettings) 
    X.ReadToDescendant("stockenquiryResult") 
    Dim Result as string = X.ReadElementContentAsString 

End Using 
+0

謝謝,但我似乎無法得到那個工作,我昨天走下這條線,但總是得到'嘗試使用'SelectS'時,'對象引用未設置爲對象的實例.' ingleNode' –

+0

對不起,我忘了SelectSingleNode需要XPath表達式。我爲XmlDocument提供的原始代碼只是使用元素名稱而不是所需的XPath表達式,這就是爲什麼您收到錯誤。如果您對XPath不熟悉,可能會非常棘手。我更新了XmlDocument的答案,使用LastChild而不是SelectSingleNode。如果您確定要檢索的元素始終是最後一個孩子,那麼這可以正常工作。如果沒有,你可以去找出正確的XPath表達式來使用SelectSingleNode。 –

+0

我對XML完全不熟悉!謝謝,使用你的第一個例子,現在一切都很好用! –