Kicker
Kicker

Reputation: 606

C# select node from XML

I have this code in C#, I need to get a Cube nodes, but my list of nodes is empty..

string url = @"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(url);

XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
manager.AddNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01");

XmlNodeList nodes = xmlDoc.SelectNodes("/gesmes:Envelope/Cube", manager);

What am I doing wrong?

Upvotes: 0

Views: 91

Answers (1)

Keith Hall
Keith Hall

Reputation: 16065

There is a default namespace http://www.ecb.int/vocabulary/2002-08-01/eurofxref which you will need to register, to access the Cube element.

Otherwise, the XPath expression tries to find an un-namespaced Cube element, which doesn't exist in the document. XPath has no concept of a default namespace.

string url = @"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(url);

XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
manager.AddNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01");
manager.AddNamespace("default", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");

XmlNodeList nodes = xmlDoc.SelectNodes("/gesmes:Envelope/default:Cube", manager);

this will access the Cube child directly under the gesmes:Envelope. Depending what you want to achieve, you may want to use one of the following XPath expressions instead:

/gesmes:Envelope/default:Cube/default:Cube/default:Cube
/gesmes:Envelope//default:Cube[@currency]
/gesmes:Envelope//default:Cube[@time]/default:Cube

Upvotes: 2

Related Questions