Your basic problem of retrieving namespaces from an XmlDocument can be solved by simply retrieving the NameTable
of the XmlDocument and creating an XmlNameSpaceManager
from it.
However, if you want to list the namespaces for some other purpose, you should check out the GetNamespacesInScope
method exposed by the XmlNamespaceManager
class as well as the XPathNavigator
class.
When using an XmlDocument, you can get an XmlNamespaceManager from it via the following code:
//Instantiate an XmlDocument object.
XmlDocument xmldoc = new XmlDocument();
//Load XML file into the XmlDocument object.
xmldoc.Load("C:\\myFile.xml");
//Instantiate an XmlNamespaceManager object.
XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmldoc.NameTable);
// Retrieve the namespaces into a Generic dictionary with string keys.
IDictionary<string, string> dic = nsMgr.GetNamespacesInScope(XmlNamespaceScope.All);
// Iterate through the dictionary.
...
In this article, Scott Hanselman presents a way to use this method to list all namespaces in a document using an XPathNavigator and using a LINQ bridge.