alexclp
alexclp

Reputation: 201

Parsing an XML in C#

I have this xml http://www.bnr.ro/nbrfxrates.xml , and I want to parse it. I have transformed it into a string, but I don't know how to iterate through the Cube's children to get the data I'm interested in (the currency rates). Any help, please? Thanks.

Upvotes: 1

Views: 303

Answers (3)

GorkemHalulu
GorkemHalulu

Reputation: 3075

You can try HtmlAgilityPack.

And by the help of XPath, all nodes become easily accessible.

Code sample:

WebRequest webRequestSearch = WebRequest.Create("http://www.bnr.ro/nbrfxrates.xml");
WebResponse webResponseSearch = webRequestSearch.GetResponse();
Stream streamSearch = webResponseSearch.GetResponseStream();
StreamReader oReaderSearch = new StreamReader(streamSearch, Encoding.GetEncoding(1254));
strTempHtml = oReaderSearch.ReadToEnd();     
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(strTempHtml);
HtmlNodeCollection nodes = htmlDoc.DocumentNode.SelectNodes("//cube/rate");
string currency1 = nodes[0].Attributes["currency"].Value;
string currency1Value =nodes[0].InnerText;

Upvotes: 2

L.B
L.B

Reputation: 116178

XNamespace ns = "http://www.bnr.ro/xsd";
var rates = XDocument.Load("http://www.bnr.ro/nbrfxrates.xml")
            .Descendants(ns + "Rate")
            .Select(r => new
            {
                Currency = r.Attribute("currency").Value,
                Value = (decimal)r,
                Multiplier = (int?)r.Attribute("multiplier")
            })
            .ToList();

Upvotes: 0

SlashJ
SlashJ

Reputation: 807

You can use LINQ to XML, there is many examples and explanations on this website:

http://www.dotnetcurry.com/showarticle.aspx?ID=564

Upvotes: 1

Related Questions