使用Linq to XML和where子句获取值

时间:2013-05-24 10:12:13

标签: linq linq-to-xml

我想将Linq用于XML,我想弄清楚如何获得货币CAD的价值,BuyRateForeign,基本上我需要获得价值5,602895。

<ExchRates>
    <ExchRate>
        <Bank>Bank</Bank>
        <CurrencyBase>USD</CurrencyBase>
        <Date>24.05.2013.</Date>
        <Currency Code="036">
            <Name>AUD</Name>
            <Unit>1</Unit>
            <BuyRateCache>5,569450</BuyRateCache>
            <BuyRateForeign>5,625707</BuyRateForeign>
            <MeanRate>5,711378</MeanRate>
            <SellRateForeign>5,797049</SellRateForeign>
            <SellRateCache>5,855019</SellRateCache>
        </Currency>
        <Currency Code="124">
            <Name>CAD</Name>
            <Unit>1</Unit>
            <BuyRateCache>5,546866</BuyRateCache>
            <BuyRateForeign>5,602895</BuyRateForeign>
            <MeanRate>5,688218</MeanRate>
            <SellRateForeign>5,773541</SellRateForeign>
            <SellRateCache>5,831276</SellRateCache>
        </Currency>
    </ExchRate>
</ExchRates>

2 个答案:

答案 0 :(得分:1)

var xDoc = XDocument.Load("path/to/your.xml");

var cadForeignBuyRate =
    xDoc.Root.Element("ExchRate").First(e => e.Element("Bank").Value == "Bank")
    .Elements("Currency").First(e => e.Element("Name").Value == "CAD")
    .Element("BuyRateForeign").Value;

答案 1 :(得分:1)

var xDoc = XDocument.Load("path/to/your.xml");    

var BuyRateForeign = from nm in xDoc.Descendants("Currency")
                     where (string)nm.Element("Name") == "CAD"
                     select (string)nm.Element("BuyRateForeign");

使用Lambda表达式

var stringRate = xDoc.Descendants("Currency")
                 .Where(p=> (string)p.Element("Name") == "CAD")
                 .Select(p => (string)p.Element("BuyRateForeign"))
                 .SingleOrDefault();