在xml中查找元素,并获取其他元素值

时间:2014-01-18 15:25:17

标签: c# xml

我的xml看起来像:

<CURRENCIES>
 <LAST_UPDATE>2014-01-17</LAST_UPDATE>
 <CURRENCY>
   <NAME>Dollar</NAME>
   <UNIT>1</UNIT>
   <CURRENCYCODE>USD</CURRENCYCODE>
   <COUNTRY>USA</COUNTRY>
   <RATE>3.489</RATE>
   <CHANGE>-0.086</CHANGE>
 </CURRENCY>
</CURRENCIES>

我想从元素“NAME”和“COUNTRY”中找到特定货币,并取值“RATE”。

我写道:

public void ConvertCurrency(int value, string currency)
    {

        WebClient webClient = new WebClient();
        XDocument xml = new XDocument();
        webClient.DownloadFile("http://www.boi.org.il/currency.xml", @"currency.xml");
        XDocument currency_xml = XDocument.Load("currency.xml");

        var findCurrency = from currency1 in currency_xml.Descendants("CURRENCIES")
                           where (Convert.ToString(currency1.Element("CURRENCY").Element("NAME").Value) == currency) && (Convert.ToString(currency1.Element("CURRENCY").Element("COUNTRY").Value) == "USA")
                           select currency1.Element("RATE").Value;
        int rate = Convert.ToInt32(findCurrency);

        int result = value * rate;
        Console.WriteLine("Result:{0}",result);

    }

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您的查询超过CURRENCIES个元素,而您只查看第一个CURRENCY个孩子。然后,您要在RATE而非CURRENCIES内寻找CURRENCY个孩子。另外,你得到一个整数的序列 - 而不是一个int。我想你想要:

// Load directly from the web - it's simpler...
XDocument doc = XDocument.Load("http://www.boi.org.il/currency.xml");
var element = doc.Root
                 .Elements("CURRENCY")
                 .Where(x => (string) x.Element("COUNTRY") == "USA") &&
                             (string) x.Element("NAME") == currency)
                 .FirstOrDefault();
if (element != null)
{
    // You don't want an int here - you shouldn't lose information!
    decimal rate = (decimal) element.Element("RATE");
    decimal result = value * rate;
    Console.WriteLine("Result: {0}", result);
}
else
{
    Console.WriteLine("Couldn't find currency rate for USA");
}

注意:

  • 我没有在这里使用查询表达式,因为它无助于简化任何事情
  • 如果CURRENCY的{​​{1}}元素没有USA元素,则会失败;你需要解决这个问题吗?
  • 我更喜欢在RATE中使用用户定义的转化,而不是使用XElement;它们专门用于XML值(例如,在转换小数值时不会使用文化)

答案 1 :(得分:0)

Jon Skeet的答案已经完成,无论如何这里是您使用LINQ语法的固定查询

var findCurrency = (from c in currency_xml.Descendants("CURRENCY")
                      where (string)c.Element("NAME") == currency
                           && (string)c.Element("COUNTRY") == "USA"
                             select (string)c.Element("RATE")).FirstOrDefault();
相关问题