Mega Code Archive

 
Categories / C# / XML
 

Gets the XML namespace manager

using System; using System.Collections.Specialized; using System.Xml; using System.Text; using System.Text.RegularExpressions; namespace RSBuild {   /// <summary>   /// Utility methods.   /// </summary>   public static class Util   {         /// <summary>         /// Gets the XML namespace manager.         /// </summary>         /// <param name="input">The input.</param>         /// <returns>The XML namespace manager</returns>     public static XmlNamespaceManager GetXmlNamespaceManager(XmlDocument input)     {       StringCollection namespaces = DetectXmlNamespace(input);       XmlNamespaceManager xnm = null;              if (namespaces != null && namespaces.Count > 0)       {         xnm = new XmlNamespaceManager(input.NameTable);         foreach(string ns in namespaces)          {           string[] arr = ns.Split('|');           xnm.AddNamespace(arr[0].Trim(), arr[1].Trim());         }       }       return xnm;     }         /// <summary>         /// Detects the XML namespace.         /// </summary>         /// <param name="doc">The doc.</param>         /// <returns></returns>     private static StringCollection DetectXmlNamespace(XmlDocument doc)      {       StringCollection detectedNamespaces = null;       if (doc != null)       {         XmlNode xmlNode = doc.DocumentElement;         detectedNamespaces = new StringCollection();         DiscoverNamespace(xmlNode, detectedNamespaces);       }       return detectedNamespaces;     }         /// <summary>         /// Discovers the namespace.         /// </summary>         /// <param name="xmlNode">The XML node.</param>         /// <param name="discovered">The discovered.</param>     private static void DiscoverNamespace(XmlNode xmlNode, StringCollection discovered)     {       string nsPrefix;       string nsUri;       if (xmlNode.NodeType == XmlNodeType.Element)        {         if (xmlNode.Attributes.Count > 0)          {           foreach(XmlAttribute attr in xmlNode.Attributes)           {             if (attr.Name.StartsWith("xmlns"))              {               string nsDef = attr.Name.Split('=')[0];               if (string.Compare(nsDef, "xmlns", true) != 0)                {                 nsPrefix = nsDef.Split(':')[1];               }               else                {                 nsPrefix = "def";               }               nsUri = attr.Value;               discovered.Add(string.Format("{0}|{1}", nsPrefix, nsUri));             }           }         }         if (xmlNode.HasChildNodes)          {           foreach(XmlNode node in xmlNode.ChildNodes)           {             DiscoverNamespace(node, discovered);           }         }       }     }   } }