Take the following XML fragment
1: <?xml version="1.0" encoding="iso-8859-1"?>
2: <con:search-results
3: xmlns:con="http://namespace.contoso.com/business-objects"
4: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5: xsi:noNamespaceSchemaLocation="http://www.contoso.com/dtd/syndication/biz-objects.xsd">
6: <con:search-query>ipod</con:search-query>
7: <con:result-count>2207</con:result-count>
8: <con:start-index>0</con:start-index>
9: <con:result-count>15</con:result-count>
10: <con:results>
11: <con:result>
12: ...
13:
Now suppose you loaded this XML into an XmlDocument, how would you query for all the <con:result> nodes? Using XPath you’d write something like
1: /search-results/results/result
So you might try writing something like
1: XmlDocument doc = new XmlDocument();
2: doc.LoadXml(response);
3: var resultNodes = doc.SelectNodes("/search-results/results/result");
but you would find that resuldNodes would be null. You have to instantiate an XmlNamespaceManager to help correctly maneuver your namespaces. That’s done like so:
1: XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
2: nsmgr.AddNamespace("con", "http://namespace.contoso.com/business-objects");
Then you would query your xml like so:
1: var resultNodes = doc.SelectNodes("/con:search-results/con:results/con:result")
That took me a little searching to dig up, but it makes sense, right?