我使用xignite API獲取實時貨幣交換數據。當我使用我的查詢字符串:在C#中使用XDoc獲取XML元素的內容
http://globalcurrencies.xignite.com/xGlobalCurrencies.xml/GetRealTimeRate?Symbol=GBPEUR&_token=[mytoken]
我得到如下:
<Rate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.xignite.com/services/">
<Outcome>Success</Outcome>
<Identity>Request</Identity>
<Delay>0.0218855</Delay>
<BaseCurrency>USD</BaseCurrency>
<QuoteCurrency>EUR</QuoteCurrency>
<Symbol>USDEUR</Symbol>
<Date>08/24/2016</Date>
<Time>3:23:34 PM</Time>
<QuoteType>Calculated</QuoteType>
<Bid>0.889126</Bid>
<Mid>0.88915</Mid>
<Ask>0.889173</Ask>
<Spread>4.74352E-05</Spread>
<Text>
1 United States dollar = 0.88915 European Union euro
</Text>
<Source>Rate calculated from EUR:USD</Source>
</Rate>
我試圖訪問Mid
元素的內容,到目前爲止,我這樣做
var xDoc = XDocument.Load(
"http://globalcurrencies.xignite.com/xGlobalCurrencies.xml/GetRealTimeRate?Symbol="
+ "GBP" + "EUR" + "&_token=[MyToken]");
string s = (string)xDoc.Root.Element("Mid");
output.Text = s;
該xDoc
變量返回與我以前顯示的XML,但當我嘗試獲取Mid
元素的內容時,string s
是null
。如何使用XDoc訪問元素Mid
的內容?
我想這一點,但我有與 NS,REG和MyObject來 他們有什麼麻煩嗎? – user3711612
問題中的代碼也使用LINQ to XML,但不起作用。我不確定通用示例將如何幫助發現當前代碼中的錯誤。 –
@ user3711612我之前的代碼存在錯誤,我修正了它... MyObject在我的示例中將是您的Rate對象,您可以直接從xml中提取並實例化速率對象,然後訪問Rate對象中的Mid屬性 – miguelmpn