在C#中将XML属性值提取为变量

时间:2015-11-05 16:10:25

标签: c# xml linq-to-xml

鉴于以下XML(来自http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml),如何将日期,美元汇率和英镑汇率作为三个单独的字符串变量提取?

<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2015-11-05">
<Cube currency="USD" rate="1.0883"/>
<Cube currency="JPY" rate="132.65"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="27.044"/>
<Cube currency="DKK" rate="7.4592"/>
<Cube currency="GBP" rate="0.71260"/>
<Cube currency="HUF" rate="313.97"/>
<Cube currency="PLN" rate="4.2392"/>
<Cube currency="RON" rate="4.4486"/>
<Cube currency="SEK" rate="9.3916"/>
<Cube currency="CHF" rate="1.0833"/>
<Cube currency="NOK" rate="9.3065"/>
<Cube currency="HRK" rate="7.5545"/>
<Cube currency="RUB" rate="68.8654"/>
<Cube currency="TRY" rate="3.1215"/>
<Cube currency="AUD" rate="1.5233"/>
<Cube currency="BRL" rate="4.1364"/>
<Cube currency="CAD" rate="1.4320"/>
<Cube currency="CNY" rate="6.9065"/>
<Cube currency="HKD" rate="8.4351"/>
<Cube currency="IDR" rate="14751.76"/>
<Cube currency="ILS" rate="4.2333"/>
<Cube currency="INR" rate="71.7100"/>
<Cube currency="KRW" rate="1240.66"/>
<Cube currency="MXN" rate="17.9972"/>
<Cube currency="MYR" rate="4.6781"/>
<Cube currency="NZD" rate="1.6450"/>
<Cube currency="PHP" rate="51.047"/>
<Cube currency="SGD" rate="1.5310"/>
<Cube currency="THB" rate="38.702"/>
<Cube currency="ZAR" rate="15.1123"/>
</Cube>
</Cube>
</gesmes:Envelope>

到目前为止,我所尝试的是无效的:

var xmlString = (new WebClient()).DownloadString("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
XDocument doc = XDocument.Parse(xmlString);
var getGBP = from d in doc.Descendants("Cube")
    where d.Element("Cube").Element("Cube").Attribute("currency").Value == "GBP"
    select d.Element("Cube").Element("Cube").Attribute("rate").Value.FirstOrDefault();

var gbpResult = getGBP.ToString();

0 个答案:

没有答案