我正在使用xignite API来获取实时货币兑换数据。当我使用查询字符串时:
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的内容?
发布于 2016-08-25 01:42:14
我使用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将包含一个来自XML文件的MyObjects数组。
编辑:由于您使用XML更新了问题,因此我认为您只缺少查询中的名称空间(我的查询中的ns ),请查看Charles Mager answer
我的答案是一种不同的方法。您保存Rate对象并使用它,而无需再次读取XML (您将需要在一个类中定义Rate )请注意我所做的值转换,您将需要匹配您的class :)
发布于 2016-08-25 16:14:52
XML中的限定名称由两部分组成:命名空间和本地名称。在您的XML中,本地名称是Mid,但是名称空间不是空的:它是http://www.xignite.com/services/,由根元素中的默认名称空间声明xmlns="..."表示。
如果你考虑到这一点,你会得到一个结果:
XNamespace ns = "http://www.xignite.com/services/";
var mid = (decimal)xDoc.Root.Element(ns + "Mid");https://stackoverflow.com/questions/39129746
复制相似问题