1

I can't seem to parse XML nodes from an URL. The project (MVC .net) I'm currently working on has a model with the data i want to bring :

    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

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? The nodes needed are the date, currency and the value of currency.

Thank you in advance for your support.

2 Answers 2

1

You can deserialize the XML into C# objects and then extract the information you need using linq.

Creating the model based on the XML schema:

[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:

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Heloo sir, i might have some questions about your solution. Did u name this model based on the schema "CurrenciesDataSet"? This new class you.ve made is a totally different one from my "ExchangeRate" class?
@LaviniaRotaru sorry I made a mistake, I edited my answer and copy/pasted the right classes. The classes I use are different from yours because I have created classes that match the XML schema of http://www.bnr.ro/nbrfxrates.xsd
0

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();" 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.