Reading Remote XML in C #

I am reading a remote XML file, and as soon as the XML is loaded into the XMLDocument object, I need to go through it and extract the values ​​that my application needs. My code is as follows:

XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"); XmlNamespaceManager nsMan = new XmlNamespaceManager(xmlDocument.NameTable); nsMan.AddNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01"); nsMan.AddNamespace("", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"); XmlNodeList xmlNodeList = xmlDocument.DocumentElement.SelectNodes("/gesmes:Envelope/Cube/Cube/Cube", nsMan); HttpContext.Current.Response.Write("The numner of nodes is " + xmlNodeList.Count); //it always zero 

However, the problem I get is that the XmlNodeList always returns zero nodes, whereas if I evaluate the XPath expression in XMLSpy, I get the required nodes.

For reference, XML looks like this:

 <?xml version="1.0" encoding="UTF-8"?> <gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"> <gesmes:subject>Reference rates</gesmes:subject> <gesmes:Sender> <gesmes:name>European Central Bank</gesmes:name> </gesmes:Sender> <Cube> <Cube time='2011-07-27'> <Cube currency='USD' rate='1.4446'/> <Cube currency='GBP' rate='0.88310'/> </Cube> </Cube> </gesmes:Envelope> 

I want to return Cube nodes for USD and GBP.

Any ideas that you are smart people?

Thanks al

+4
source share
1 answer

Although you can definitely work with namespaces and XPath in the XmlDocument API, I highly recommend that you use LINQ to XML (.NET 3.5), if at all possible:

 string url = "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"; XDocument doc = XDocument.Load(url); XNamespace gesmes = "http://www.gesmes.org/xml/2002-08-01"; XNamespace ns = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"; var cubes = doc.Descendants(ns + "Cube") .Where(x => x.Attribute("currency") != null) .Select(x => new { Currency = (string) x.Attribute("currency"), Rate = (decimal) x.Attribute("rate") }); foreach (var result in cubes) { Console.WriteLine("{0}: {1}", result.Currency, result.Rate); } 
+12
source

All Articles