How can I get all namespaces in scope for a specific XmlElement?

David Thielen 2,526 Reputation points
2020-12-13T20:28:05.517+00:00

Hi all;

I am editing an XmlDocument and at a given XmlElement, I need to know all prefixes/URIs that are in scope for the element as namespaces? Is there a way to do this? (There's lot's of examples to get all namespaces in the entire document, but I can't find any that limit it to what's in scope.)

This is some existing code and changing to XDocument or LINQ is a no-go.

thanks - dave

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,136 questions
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,576 Reputation points
    2020-12-17T08:11:35.33+00:00

    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.


0 additional answers

Sort by: Most helpful