简体   繁体   中英

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.

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;

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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