简体   繁体   English

从MVC .net中的XML URL文件获取节点

[英]Get nodes from XML URL file in MVC .net

I can't seem to parse XML nodes from an URL. 我似乎无法从URL解析XML节点。 The project (MVC .net) I'm currently working on has a model with the data i want to bring : 我目前正在研究的项目(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; }

    }
}

Then this is my controller (I've tried different kind of methods including nodes, but I've stopped at this one) : 然后,这就是我的控制器(我尝试了包括节点在内的其他方法,但是我停止了这种方法):

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;
        }
    }
}

This is the XML I'm trying to get info from : http://www.bnr.ro/nbrfxrates.xml 这是我正在尝试从以下网站获取信息的XML: http : //www.bnr.ro/nbrfxrates.xml

Also, the view would look like this: 此外,视图将如下所示:

@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>

How would I search for the nodes of XML file and also bring these nodes in the view? 我将如何搜索XML文件的节点并将这些节点显示在视图中? The nodes needed are the date, currency and the value of currency. 所需的节点是日期,货币和货币值。

Thank you in advance for your support. 预先感谢您对我们的支持。

You can deserialize the XML into C# objects and then extract the information you need using linq. 您可以将XML反序列化为C#对象,然后使用linq提取所需的信息。

Creating the model based on the XML schema : 基于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; }
}

Deserializing the XML and getting the data - example: 反序列化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();
}

Yes, I've checked in all that's been modified. 是的,我已经检查了所有已修改的内容。

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;
        }
    }
}

This being my controller "dataset.Body.Cubes.FirstOrDefault();" 这是我的控制器“ dataset.Body.Cubes.FirstOrDefault();” will be null. 将为空。

This is how i call my controller in view: 这是我如何在视图中称呼我的控制器:

@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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM