Please try if this code meets your requirements.
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load(@"d:\test\xml\test.xml");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("z", "uriZ");
XmlNode nodemsg = doc.SelectSingleNode("//z:person", nsmgr);
IDictionary<string, string> result = getNamespacesInScope(nodemsg);
}
public static IDictionary<string, string> getNamespacesInScope(XmlNode xDoc)
{
IDictionary<string, string> AllNamespaces = new Dictionary<string,string>();
IDictionary<string, string> localNamespaces;
XmlNode temp = xDoc;
XPathNavigator xNav;
while (temp.ParentNode!=null)
{
xNav = temp.CreateNavigator();
localNamespaces = xNav.GetNamespacesInScope(XmlNamespaceScope.Local);
foreach (var item in localNamespaces)
{
if (!AllNamespaces.ContainsKey(item.Key))
{
AllNamespaces.Add(item);
}
}
temp = temp.ParentNode;
}
return AllNamespaces;
}
Example xml I used:
<?xml version="1.0" encoding="utf-8" ?>
<x:root xmlns:x="ur11" xmlns:y="uri2" xmlns:z="uri3">
<y:employees xmlns:y="uriA">
<z:person xmlns:z ="uriZ"/>
</y:employees>
</x:root>
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.