C# – Why the XPath request to XML file on web doesn’t work

cnetweb servicesxmlxpath

There is an XML file with exchange rates http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml:

<gesmes:Envelope>
  <gesmes:subject>Reference rates</gesmes:subject>
  <gesmes:Sender>
    <gesmes:name>European Central Bank</gesmes:name>
  </gesmes:Sender>
  <Cube>
    <Cube time="2009-11-26">
      <Cube currency="USD" rate="1.5071"/>
       ...

I do next XPath request:

var doc = new XmlDocument();
doc.Load(url);
var node = doc.SelectSingleNode("//Cube[@currency=\"USD\""]);
var value = node.Attributes["rate"].Value;

but it returns null! Where is my mistake?

If I do this request, all works fine:

var node = dic.SelectSingleNode("//*[@currency=\"USD\"]");
var name = node.Name; // "Cube"

Best Answer

Try

var node = doc.SelectSingleNode("//*[local-name()='Cube' and @currency=\"USD\""]);

you can always add in the namespace if you know it

var node = doc.SelectSingleNode("//*[local-name()='Cube' and 
     namespace-uri()='http://www.ecb.int/vocabulary/2002-08-01/eurofxref' and
     @currency=\"USD\""]);

Although it's longwinded I prefer it to trying to sort out namespace prefixes. And it also avoids the problem of the default namespace (xmlns="")

Related Topic