0

我正在使用 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 snull. 如何Mid使用 XDoc 访问元素的内容?

4

2 回答 2

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 将包含来自 XML 文件的 MyObjects 数组。

编辑:由于您使用 XML 更新了您的问题,我认为您只是缺少查询中的名称空间(我的查询中的 ns),请查看 Charles Mager 的答案

我的答案是另一种方法..您保存 Rate 对象并使用它而无需再次读取 XML(您需要在类中定义 Rate)小心我所做的值转换,您需要匹配你的班级:)

于 2016-08-24T17:42:13.643 回答
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");
于 2016-08-25T08:14:52.480 回答