Кажется, я не могу анализировать узлы XML из URL-адреса. В проекте (MVC .net), над которым я сейчас работаю, есть модель с данными, которые я хочу предоставить:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyHR.Domain.Models
{
public class ExchangeRate
{
public string DataCurenta { get; set; }
public string Moneda { get; set; }
public string Valoarea { get; set; }
}
}
Тогда это мой контроллер (я пробовал разные методы, включая узлы, но остановился на этом):
using MyHR.Domain.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Linq;
namespace MyHR.Web.Controllers
{
public class ExchangeRateController : Controller
{
// GET: ExchangeRate
public ActionResult DisplayXml(List<ExchangeRate> exchangeRates)
{
List<ExchangeRate> data = new List<ExchangeRate>();
data = ReturnData();
return View(data);
}
public List<ExchangeRate> ReturnData()
{
string xmldata = @"http://www.bnr.ro/nbrfxrates.xml";
XDocument Xml = XDocument.Load(xmldata);
XDocument doc = new XDocument();
DataSet ds = new DataSet();
ds.ReadXml(xmldata);
//Loop through the selected Nodes.
//XmlNodeList xmlDate = doc.GetElementsByTagName("Cube");
//XmlNodeList listdata = doc.GetElementsByTagName("Rate");
var ratelist = new List<ExchangeRate>();
ratelist = (from ReturnData in doc.Descendants("Cube").Descendants()
select new ExchangeRate
{
DataCurenta = ReturnData.Element("date").ToString(),
//Moneda = ReturnData.Element("currency").ToString(),
//Valoarea = ReturnData.Element("description").ToString(),
}).ToList();
return ratelist;
}
}
}
Это XML, из которого я пытаюсь получить информацию: http://www.bnr.ro/nbrfxrates.xml
Кроме того, вид будет выглядеть так:
@using MyHR.Domain.Models
@model IEnumerable<MyHR.Domain.Models.ExchangeRate>
@{
/**/
ViewBag.Title = "DisplayXml";
}
<br><br />
<h1 align = "center">Cursul valutar din data curenta</h1>
<br><br />
<meta name = "Curs Valutar" content = "width=device-width" />
<title>Index</title>
<table class = "table table-responsive table-bordered">
<thead style = "background-color:#88D0AA">
<tr align = "center">
<th align = "center">
DataCurenta
</th>
<th align = "center">
Moneda
</th>
<th align = "center">
Valoarea
</th>
</tr>
</thead>
<tbody>
@foreach (ExchangeRate exchange in Model)
{
<tr>
<td>@exchange.DataCurenta</td>
<td>@exchange.Moneda</td>
<td>@exchange.Valoarea</td>
</tr>
}
</tbody>
</table>
Как мне искать узлы XML-файла, а также отображать эти узлы в представлении? Необходимые узлы - это дата, валюта и стоимость валюты.
Спасибо заранее за вашу поддержку.





Вы можете десериализовать XML в объекты C#, а затем извлечь необходимую информацию с помощью linq.
Создание модели на основе Схема XML:
[Serializable]
[XmlRoot("DataSet", Namespace = "http://www.bnr.ro/xsd", IsNullable = false)]
public class CurrenciesDataSet
{
public Header Header { get; set; }
public Body Body { get; set; }
}
[Serializable]
public class Header
{
public string Publisher { get; set; }
[XmlElement(DataType = "date")]
public DateTime PublishingDate { get; set; }
public string MessageType { get; set; }
}
[Serializable]
public class Cube
{
[XmlElement("Rate")]
public List<Rate> Rates { get; set; }
[XmlAttribute("date")]
public string Date { get; set; }
}
[Serializable]
public class Rate
{
[XmlAttribute("currency")]
public string Currency { get; set; }
[XmlAttribute("multiplier")]
public int Multiplier { get; set; }
[XmlText]
public decimal Value { get; set; }
}
[Serializable]
public class Body
{
public string Subject { get; set; }
public string Description { get; set; }
public string OrigCurrency { get; set; }
[XmlElement("Cube")]
public List<Cube> Cubes { get; set; }
}
Десериализация XML и получение данных - пример:
CurrenciesDataSet dataset = null;
var rates = new List<ExchangeRate>();
XDocument doc = XDocument.Load(@"http://www.bnr.ro/nbrfxrates.xml");
using (TextReader sr = new StringReader(doc.ToString(SaveOptions.DisableFormatting)))
{
var serializer = new XmlSerializer(typeof(CurrenciesDataSet));
dataset = (CurrenciesDataSet)serializer.Deserialize(sr);
}
// According to the schema there might be multiple <Cube> elements,
// which one do you want??
Cube cube = dataset.Body.Cubes.FirstOrDefault();
if (cube != null)
{
rates = cube.Rates.Select(x => new ExchangeRate
{
DataCurenta = cube.Date,
Moneda = x.Currency,
// ....
}).ToList();
}
@LaviniaRotaru, извините, я сделал ошибку, я отредактировал свой ответ и скопировал / вставил правильные классы. Классы, которые я использую, отличаются от ваших, потому что я создал классы, соответствующие XML-схеме http://www.bnr.ro/nbrfxrates.xsd
Да, я проверил все, что было изменено.
using MyHR.Domain.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using static MyHR.Domain.Models.CurrencyDataSet;
namespace MyHR.Web.Controllers
{
public class ExchangeRateController : Controller
{
// // GET: ExchangeRate
public ActionResult ExchangeRate(List<ExchangeRate> data)
{
{
data = new List<ExchangeRate>();
data = exchangeRates();
return View(data);
}
}
public List<ExchangeRate> exchangeRates()
{
CurrenciesDataSet dataset = null;
List<ExchangeRate> rates = new List<ExchangeRate>();
XDocument doc = XDocument.Load(@"http://www.bnr.ro/nbrfxrates.xml");
using (TextReader sr = new StringReader(doc.ToString(SaveOptions.DisableFormatting)))
{
var serializer = new XmlSerializer(typeof(CurrenciesDataSet));
dataset = (CurrenciesDataSet)serializer.Deserialize(sr);
}
Cube cube = dataset.Body.Cubes.FirstOrDefault();
if (cube != null)
{
rates = cube.Rates.Select(x => new ExchangeRate
{
DataCurenta = cube.Date,
Moneda = x.Currency,
Valoarea = x.Multiplier.ToString(),
}).ToList();
}
return rates;
}
}
}
Это мой контроллер "dataset.Body.Cubes.FirstOrDefault ();" будет нулевым.
Вот как я называю свой контроллер в поле зрения:
@using MyHR.Domain.Models
@model IEnumerable<ExchangeRate>
<br><br />
<h1 align = "center">Cursul valutar din data curenta</h1>
<br><br />
<meta name = "Curs Valutar" content = "width=device-width" />
<title>Index</title>
<table class = "table table-responsive table-bordered">
<thead style = "background-color:#88D0AA">
<tr align = "center">
<th align = "center">
DataCurenta
</th>
<th align = "center">
Moneda
</th>
<th align = "center">
Valoarea
</th>
</tr>
</thead>
<tbody>
@foreach (ExchangeRate exchange in Model)
{
<tr>
<td>@exchange.DataCurenta</td>
<td>@exchange.Moneda</td>
<td>@exchange.Valoarea</td>
</tr>
}
</tbody>
</table>
Здравствуйте, сэр, у меня могут возникнуть вопросы по поводу вашего решения. Вы назвали эту модель на основе схемы "CurrenciesDataSet"? Этот новый класс, который вы создали, полностью отличается от моего класса "ExchangeRate"?