Reputation: 475
I'm trying to read some XML:
<?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='2015-02-23'>
<Cube currency='USD' rate='1.1298'/>
<Cube currency='JPY' rate='134.50'/>
<Cube currency='BGN' rate='1.9558'/>
<Cube currency='CZK' rate='27.444'/>
</Cube>
</Cube>
</gesmes:Envelope>
I'm parsing that stuff with following code:
var path = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
string xml;
using (var wc = new WebClient())
{
xml = wc.DownloadString(path);
}
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNamespaceManager mgr = new XmlNamespaceManager(xmlDoc.NameTable);
mgr.AddNamespace("n", "http://www.gesmes.org/xml/2002-08-01");
1.) XmlNodeList cubes = xmlDoc.SelectNodes("/n:Envelope", mgr); //WORKS
2.) XmlNodeList cubes = xmlDoc.SelectNodes("/n:Envelope/Cube", mgr); //DOES NOT WORK
foreach (XmlNode c in cubes)
{
// whatever
}
When I open the Envelope-node (1.), it works. But I have no idea, how to access the sub-nodes within the namespace-node (2.). That code runs, but returns no result. How to access that?
Upvotes: 0
Views: 95
Reputation: 15578
There's a default namespace declared in the Envelope-element. Any descendant of that element that doesn't have an explicit namespace declared will have the default namespace.
XmlNamespaceManager mgr = new XmlNamespaceManager(xmlDoc.NameTable);
mgr.AddNamespace("n", "http://www.gesmes.org/xml/2002-08-01");
mgr.AddNamespace("d", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
XmlNodeList cubes = xmlDoc.SelectNodes("/n:Envelope/d:Cube", mgr);
will work. Note the added namespace to stand in for the default one, both in the manager and in the xpath. If you inspect the result of that, you will find
<Cube xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<Cube time="2015-02-23">
<Cube currency="USD" rate="1.1298" />
<Cube currency="JPY" rate="134.50" />
<Cube currency="BGN" rate="1.9558" />
<Cube currency="CZK" rate="27.444" />
</Cube>
</Cube>
which clearly states there's a default namespace belonging to the outermost Cube element which is, in this xml fragment, the root.
Upvotes: 2