在c#中使用XDoc获取XML元素的内容

本文关键字:元素 XML 获取 XDoc | 更新日期: 2023-09-27 18:03:53

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

在c#中使用XDoc获取XML元素的内容

XML中的限定名由两部分组成:名称空间和本地名称。在XML中,本地名称是Mid,但是名称空间不是空:它是http://www.xignite.com/services/,如根元素中的默认名称空间声明xmlns="..."所示。

如果你考虑到这一点,你将得到一个结果:

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

我使用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)。注意我所做的值转换,您需要匹配您的类:)

相关文章: