2016-08-24 62 views
0

我使用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 snull。如何使用XDoc訪問元素Mid的內容?

回答

0

我使用Linq to XML,這裏是一個例子

XNamespace ns = "http://www.xignite.com/services/"; 
XDocument xdoc = XDocument.Load(xmlPath); 
var rateMids = (from obj in xdoc.Descendants(ns + "Rate") 
       select new Rate 
       (
         obj.Attribute("Outcome").Value, 
         obj.Attribute("Identity").Value, 
         (decimal)obj.Attribute("Delay").Value, 
         obj.Attribute("BaseCurrency").Value, 
         obj.Attribute("QuoteCurrency").Value, 
         obj.Attribute("Symbol").Value, 
         DateTime.Parse(obj.Attribute("Date").Value), 
         obj.Attribute("Time").Value.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture), 
         obj.Attribute("QuoteType").Value, 
         (decimal)obj.Attribute("Bid").Value, 
         (decimal)obj.Attribute("Mid").Value, 
         (decimal)obj.Attribute("Ask").Value, 
         Convert.ToInt32(obj.Attribute("Spread").Value), 
         Convert.ToInt32(obj.Attribute("Text").Value) 
       ) 
       ).ToArray(); 

myObjects將包含MyObjects的XML文件中的陣列。

編輯:既然你用XML更新你的問題,我想你是唯一缺少對查詢的命名空間(我的查詢NS),請採取查爾斯馬傑回答看看

我的答案是不同的方法..您保存Rate對象並使用它,而無需再次讀取XML(您需要在類中定義費率) 請注意我所做的值轉換,您需要匹配您的類: )

+0

我想這一點,但我有與 NS,REG和MyObject來 他們有什麼麻煩嗎? – user3711612

+0

問題中的代碼也使用LINQ to XML,但不起作用。我不確定通用示例將如何幫助發現當前代碼中的錯誤。 –

+0

@ user3711612我之前的代碼存在錯誤,我修正了它... MyObject在我的示例中將是您的Rate對象,您可以直接從xml中提取並實例化速率對象,然後訪問Rate對象中的Mid屬性 – miguelmpn

0

XML中的限定名由兩部分組成:名稱空間和本地名。在您的XML中,您的本地名稱是Mid,但您的名稱空間是而不是空:它是http://www.xignite.com/services/,如根元素中默認名稱空間聲明xmlns="..."所示。

如果你考慮到這一點,你會得到一個結果:

XNamespace ns = "http://www.xignite.com/services/"; 
var mid = (decimal)xDoc.Root.Element(ns + "Mid");