LINQ to XML. NullReferenceExeption при чтении атрибутов - C#
Формулировка задачи:
Здравствуйте. Нужна помощь, пробую распарсить ствоку но выдает NullReferenceExeption. Сделал похожый пример, он работает нормально.
XML который я пытаюсь распарсить:
Сам код метода который парсит XML и на 7-12 строке выдает NullReferenceExeption
Код метода который передает строку XML
<exchangerates>
<row>
<exchangerate ccy="RUR" base_ccy="UAH" buy="0.37817" sale="0.37817"/>
</row>
<row>
<exchangerate ccy="EUR" base_ccy="UAH" buy="18.03042" sale="18.03042"/>
</row>
<row>
<exchangerate ccy="USD" base_ccy="UAH" buy="13.65941" sale="13.65941"/>
</row>
</exchangerates>
static List<Curency> Parse(string inputXml)
{
XDocument xdoc = XDocument.Parse(inputXml);
List<Curency> outputList = new List<Curency>();
var currency = from ccr in xdoc.Element("exchangerates").Elements("row")
select new Curency
{
Type = ccr.Attribute("ccy").Value,
Buy = Convert.ToDecimal(ccr.Attribute("buy").Value),
Sale = Convert.ToDecimal(ccr.Attribute("sale").Value)
};
foreach (var ccr in currency)
{
outputList.Add(ccr);
}
return outputList;
}public static List<Curency> GetCurrency()
{
string responseXML = "";
WebRequest request = WebRequest.Create("https://api.privatbank.ua/p24api/pubinfo?exchange&coursid=5");
WebResponse response = request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
responseXML = reader.ReadToEnd();
}
}
return Parse(responseXML);
}Решение задачи: «LINQ to XML. NullReferenceExeption при чтении атрибутов»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Globalization;
namespace ConsoleApplication19 {
class Program {
static void Main(string[] args) {
XDocument doc = XDocument.Load(@"C:\test.xml");
var currency = doc.Descendants("exchangerate").Select(item =>
new Currency {
Type = item.Attribute("ccy").Value,
Buy = decimal.Parse(item.Attribute("buy").Value, NumberStyles.Currency, NumberFormatInfo.InvariantInfo),
Sale = decimal.Parse(item.Attribute("sale").Value, NumberStyles.Currency, NumberFormatInfo.InvariantInfo)
});
foreach(var c in currency){
Console.WriteLine(c);
}
Console.ReadLine();
}
}
class Currency {
public string Type { get; set; }
public decimal Buy { get; set; }
public decimal Sale { get; set; }
public override string ToString() {
return string.Format("Type: {0} Buy: {1} Sale: {2}", Type, Buy, Sale);
}
}
}