/// <summary> /// Creates a <see cref="XmlNamespaceManager"/> for <paramref name="document"/>. /// Namespaces declared in the document node are automatically added. /// The default namespace is given the prefix 'ns'. /// </summary> public static XmlNamespaceManager CreateNamespaceManager(this XmlDocument document) { var manager = new XmlNamespaceManager(document.NameTable); foreach (XmlNode node in document.SelectNodes("//node()")) { if (node is XmlElement) { var element = node as XmlElement; foreach (XmlAttribute attribute in element.Attributes) { if (attribute.Name == "xmlns") { // The first default namespace wins // (since using multiple default namespaces in a single file is not considered a good practice) if (!manager.HasNamespace("ns")) { manager.AddNamespace("ns", attribute.Value); } } if (attribute.Prefix == "xmlns") { manager.AddNamespace(attribute.LocalName, attribute.Value); } } } } return manager; }
public static XmlNamespaceManager GetNamespaceManager(IEnumerable<NodeInfo> nodes) { XmlNamespaceManager nm = new XmlNamespaceManager(new NameTable()); foreach (NodeInfo info in nodes) { foreach (string namespaceUri in info.namespaces.Keys) { string prefix = info.namespaces[namespaceUri]; if (!nm.HasNamespace(prefix)) nm.AddNamespace(prefix, namespaceUri); } } return nm; }
/// <summary> /// 获得xmlDoc指定的Xml文档对象中的NameSpaceManager对象 /// </summary> /// <param name="xmlDoc">被处理的XML文档对象(一般是XSD文件内容)</param> /// <returns>此XML的NameSpceManage对象</returns> /// <remarks> /// 获得xmlDoc指定的Xml文档对象中的NameSpaceManager对象,本函数一般用于对于一些特殊形式的 /// XML文档对象作处理。例如 /// <code> /// <DOC:INFO> /// <GUI:NODE name="hello">特殊化</GUI:NODE> /// </DOC:INFO> /// </code> /// 一类的XML文档对象。 /// <seealso cref="System.Xml.XmlNamespaceManager"/> /// </remarks> private static XmlNamespaceManager GetNSMgr(XmlDocument xmlDoc) { XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable); if (nsMgr.HasNamespace("xs") == false) nsMgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); if (nsMgr.HasNamespace("msdata") == false) nsMgr.AddNamespace("msdata", "urn:schemas-microsoft-com:xml-msdata"); return nsMgr; }
private bool ExecuteCore(string filename) { XmlDocument = new XmlDocument(); Modified = false; try { if (!string.IsNullOrEmpty(filename) && System.IO.File.Exists(filename)) { // load the file try { XmlDocument.Load(filename); } catch (XmlException ex) { Log.LogError("Invalid XML near line {0}, position {1}", ex.LineNumber, ex.LinePosition); return false; } } else if (!AllowEmptyDocument) { // if empty documents are not allowed, error out now Log.LogError("File not found: {0}", File); return false; } XPathNamespaceManager = new XmlNamespaceManager(XmlDocument.NameTable); if (!string.IsNullOrEmpty(XPathNamespaces)) { foreach (var declaration in XPathNamespaces.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)) { var index = declaration.IndexOf('='); if (index < 0) { Log.LogError("XML namespace declarations should be formatted as a semicolon-delimited list of PREFIX=URI entries"); return false; } var prefix = declaration.Substring(0, index); var uri = declaration.Substring(index + 1); if (XPathNamespaceManager.HasNamespace(prefix)) { Log.LogError("Duplicate declaration for XML namespace prefix {0}", prefix); return false; } XPathNamespaceManager.AddNamespace(prefix, uri); } } // perform the task var result = PerformTask(); if (result && Modified) { // save output if task was successful and changes were made if (!string.IsNullOrEmpty(filename)) XmlDocument.Save(filename); } return result; } #if !DEBUG catch (Exception ex) { Log.LogErrorFromException(ex); return false; } #endif finally { XPathNamespaceManager = null; XmlDocument = null; Modified = false; } }
/// <summary> /// Removes the ViewStateInformation of the VS-Designer from the Xaml(x). /// </summary> private void RemoveViewStateInformation() { log.Debug("Removing XAML(X) ViewState Information..."); // Load DOM from File XmlDocument doc = new XmlDocument(); doc.Load(inputFile); XPathNavigator navigator = doc.CreateNavigator(); // Select top node navigator.MoveToFollowing(XPathNodeType.Element); IDictionary<string, string> nsDictionary = navigator.GetNamespacesInScope(XmlNamespaceScope.All); XmlNamespaceManager namespaces = new XmlNamespaceManager(navigator.NameTable); // Add all Namespaces foreach (KeyValuePair<String, String> ns in nsDictionary.ToList()) { namespaces.AddNamespace(ns.Key, ns.Value); } // Infos String prefix; // Remove DesignerInformation String expr = "/*[@mc:Ignorable]"; if (namespaces.HasNamespace("mc")) { XmlNode att = doc.SelectSingleNode(expr, namespaces); if (att != null && !att.Attributes.GetNamedItem("mc:Ignorable").Value.Equals("")) { prefix = att.Attributes.GetNamedItem("mc:Ignorable").Value; namespaces.AddNamespace(prefix, "http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation"); // Remove Attribute att.Attributes.RemoveNamedItem("mc:Ignorable"); // Namespace XmlElement root = doc.DocumentElement; root.Attributes.RemoveNamedItem("xmlns:mc"); // ViewStateNamespace root.Attributes.RemoveNamedItem("xmlns:" + prefix); // Elements expr = "//" + prefix + ":*"; XmlNodeList nodes = doc.SelectNodes(expr, namespaces); foreach (XmlNode n in nodes) { n.ParentNode.RemoveChild(n); } // Attributes expr = "//*[@" + prefix + ":*]"; nodes = doc.SelectNodes(expr, namespaces); foreach (XmlNode n in nodes) { List<String> attributeNames = new List<string>(); // Collect (API Workaround) foreach (XmlAttribute attribute in n.Attributes) { if (attribute.NamespaceURI.Equals("http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation")) { attributeNames.Add(attribute.Name); } } // Remove foreach (String name in attributeNames) { n.Attributes.RemoveNamedItem(name); } } } else { log.Debug("Warning: No Xaml(x) Viewstate Information found."); } } doc.Save(outputFile); log.Info("Removed XAML(X) ViewState Information."); }
/// <summary> /// Remove extra unused namespace declarations. /// </summary> /// <param name="document">The current document.</param> private void RemoveUnusedNamespaces(XmlDocument document) { try { XmlNamespaceManager v_namespaceManager; List<XmlNode> v_attribues = new List<XmlNode>(); #if DEBUG_NOT WriteMessage (MessageLevel.Info, " RemoveUnusedNamespaces"); #endif v_namespaceManager = new XmlNamespaceManager(document.NameTable); v_namespaceManager.AddNamespace("xhtml", s_xhtmlNamespace); if((document.DocumentElement != null) && (document.DocumentElement.Attributes != null)) { foreach(XmlNode v_attribute in document.DocumentElement.Attributes) { if(String.Compare(v_attribute.Prefix, "xmlns", StringComparison.OrdinalIgnoreCase) == 0) { v_attribues.Add(v_attribute); if(!v_namespaceManager.HasNamespace(v_attribute.LocalName)) { v_namespaceManager.AddNamespace(v_attribute.LocalName, v_attribute.Value); } } } foreach(XmlNode v_attribute in v_attribues) { #if DEBUG_NOT WriteMessage (MessageLevel.Info, " Check namespace [{0}] [{1}]", v_attribute.LocalName, v_attribute.Name); #endif XmlNode v_namespaceUsed = null; if(v_attribute.LocalName.ToLowerInvariant() != "xhtml") v_namespaceUsed = document.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, "(/*//{0}:*) | (/*//*[@{0}:*])", v_attribute.LocalName), v_namespaceManager); if(v_namespaceUsed != null) { #if DEBUG_NOT WriteMessage(MessageLevel.Info, " Used [{0}] [{1}] [{2}] [{3}]", v_namespaceUsed.Prefix, v_namespaceUsed.LocalName, v_namespaceUsed.Name, v_namespaceUsed.NamespaceURI); WriteMessage(MessageLevel.Info, " Used [{0}]", v_namespaceUsed.OuterXml); #endif } else { document.DocumentElement.Attributes.RemoveNamedItem(v_attribute.Name); } } // The default namespace needs to be removed for future XPath queries to work. // It will be added again if necessary by the SaveComponent. document.DocumentElement.SetAttribute("xmlns", String.Empty); } } catch(Exception exp) { WriteMessage(MessageLevel.Error, exp.Message); } }
public static XmlNamespaceManager GetNamespaceScope(XmlNode context) { XmlDocument owner = null; if (context is XmlDocument) { owner = (XmlDocument)context; } else { owner = context.OwnerDocument; } XmlNameTable nt = owner.NameTable; XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt); XmlNode parent = context; while (parent != null) { if (parent is XmlElement){ if (parent.Attributes != null) { foreach (XmlAttribute a in parent.Attributes) { if (a.NamespaceURI == XmlnsUri) { string prefix = nt.Add(a.LocalName); if (prefix == "xmlns") prefix = ""; if (!nsmgr.HasNamespace(prefix)) { nsmgr.AddNamespace(prefix, nt.Add(a.Value)); } } } } } parent = parent.ParentNode; } return nsmgr; }
/// <inheritdoc /> public override void Apply(XmlDocument document, string key) { XmlElement html = document.DocumentElement; XmlNode head = html.SelectSingleNode(Help2XPath.Head); if(head == null) { head = document.CreateElement(Help2XPath.Head); if(!html.HasChildNodes) html.AppendChild(head); else html.InsertBefore(head, html.FirstChild); } else { // !EFW - Remove the unnecessary Help 2 CSS link element from the header XmlNode hxLink = head.SelectSingleNode(Help2XPath.HxLink); if(hxLink != null) head.RemoveChild(hxLink); } // Apply some fix-ups if not branding aware if(head.SelectSingleNode("meta[@name='BrandingAware']") == null) { ModifyAttribute(document, "id", "mainSection"); ModifyAttribute(document, "class", "members"); } AddMHSMeta(head, MHSMetaName.SelfBranded, _selfBranded.ToString().ToLowerInvariant()); AddMHSMeta(head, MHSMetaName.TopicVersion, _topicVersion); string locale = _locale; string id = Guid.NewGuid().ToString(); XmlNode xml = head.SelectSingleNode(Help2XPath.Xml); if(xml != null) { XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable); if(!nsmgr.HasNamespace(Help2Namespace.Prefix)) nsmgr.AddNamespace(Help2Namespace.Prefix, Help2Namespace.Uri); XmlElement elem = xml.SelectSingleNode(Help2XPath.TocTitle, nsmgr) as XmlElement; if(elem != null) AddMHSMeta(head, MHSMetaName.Title, elem.GetAttribute(Help2Attr.Title)); foreach(XmlElement keyword in xml.SelectNodes(String.Format(CultureInfo.InvariantCulture, Help2XPath.Keyword, Help2Value.K), nsmgr)) AddMHSMeta(head, MHSMetaName.Keywords, keyword.GetAttribute(Help2Attr.Term), true); foreach(XmlElement keyword in xml.SelectNodes(String.Format(CultureInfo.InvariantCulture, Help2XPath.Keyword, Help2Value.F), nsmgr)) AddMHSMeta(head, MHSMetaName.F1, keyword.GetAttribute(Help2Attr.Term), true); foreach(XmlElement lang in xml.SelectNodes(String.Format(CultureInfo.InvariantCulture, Help2XPath.Attr, Help2Value.DevLang), nsmgr)) AddMHSMeta(head, MHSMetaName.Category, Help2Value.DevLang + ":" + lang.GetAttribute(Help2Attr.Value), true); elem = xml.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, Help2XPath.Attr, Help2Value.Abstract), nsmgr) as XmlElement; if(elem != null) AddMHSMeta(head, MHSMetaName.Description, elem.GetAttribute(Help2Attr.Value)); elem = xml.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, Help2XPath.Attr, Help2Value.AssetID), nsmgr) as XmlElement; if(elem != null) id = elem.GetAttribute(Help2Attr.Value); if(String.IsNullOrEmpty(locale)) { elem = xml.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, Help2XPath.Attr, Help2Value.Locale), nsmgr) as XmlElement; if(elem != null) locale = elem.GetAttribute(Help2Attr.Value); } // !EFW - Remove the XML data island as it serves no purpose head.RemoveChild(xml); } if(String.IsNullOrEmpty(locale)) locale = MHSDefault.Locale; AddMHSMeta(head, MHSMetaName.Locale, locale); AddMHSMeta(head, MHSMetaName.TopicLocale, locale); AddMHSMeta(head, MHSMetaName.Id, id); TocInfo tocInfo; if(_toc.TryGetValue(id, out tocInfo)) { AddMHSMeta(head, MHSMetaName.TocParent, tocInfo.Parent); if(tocInfo.Parent != MHSDefault.TocParent) AddMHSMeta(head, MHSMetaName.TocParentVersion, tocInfo.ParentVersion); AddMHSMeta(head, MHSMetaName.TocOrder, tocInfo.Order.ToString(CultureInfo.InvariantCulture)); } }
/// <summary> /// Applies Microsoft Help System transformation to the output document. /// </summary> /// <param name="document">The <see cref="XmlDocument"/> to apply transformation to.</param> /// <param name="key">Topic key of the output document.</param> public override void Apply(XmlDocument document, string key) { _document = document; ModifyAttribute("id", "mainSection"); ModifyAttribute("class", "members"); FixHeaderBottomBackground("nsrBottom", "headerBottom"); XmlElement html = _document.DocumentElement; _head = html.SelectSingleNode(Help2XPath.Head); if (_head == null) { _head = document.CreateElement(Help2XPath.Head); if (!html.HasChildNodes) html.AppendChild(_head); else html.InsertBefore(_head, html.FirstChild); } AddMHSMeta(MHSMetaName.SelfBranded, _selfBranded.ToString().ToLower()); AddMHSMeta(MHSMetaName.ContentType, MHSDefault.Reference); AddMHSMeta(MHSMetaName.TopicVersion, _topicVersion); string locale = _locale; string id = Guid.NewGuid().ToString(); _xml = _head.SelectSingleNode(Help2XPath.Xml); if (_xml != null) { XmlNamespaceManager nsmgr = new XmlNamespaceManager(_document.NameTable); if (!nsmgr.HasNamespace(Help2Namespace.Prefix)) nsmgr.AddNamespace(Help2Namespace.Prefix, Help2Namespace.Uri); XmlElement elem = _xml.SelectSingleNode(Help2XPath.TocTitle, nsmgr) as XmlElement; if (elem != null) AddMHSMeta(MHSMetaName.Title, elem.GetAttribute(Help2Attr.Title)); foreach (XmlElement keyword in _xml.SelectNodes(string.Format(Help2XPath.Keyword, Help2Value.K), nsmgr)) AddMHSMeta(MHSMetaName.Keywords, keyword.GetAttribute(Help2Attr.Term), true); foreach (XmlElement keyword in _xml.SelectNodes(string.Format(Help2XPath.Keyword, Help2Value.F), nsmgr)) AddMHSMeta(MHSMetaName.F1, keyword.GetAttribute(Help2Attr.Term), true); foreach (XmlElement lang in _xml.SelectNodes(string.Format(Help2XPath.Attr, Help2Value.DevLang), nsmgr)) AddMHSMeta(MHSMetaName.Category, Help2Value.DevLang + ":" + lang.GetAttribute(Help2Attr.Value), true); elem = _xml.SelectSingleNode(string.Format(Help2XPath.Attr, Help2Value.Abstract), nsmgr) as XmlElement; if (elem != null) AddMHSMeta(MHSMetaName.Description, elem.GetAttribute(Help2Attr.Value)); elem = _xml.SelectSingleNode(string.Format(Help2XPath.Attr, Help2Value.AssetID), nsmgr) as XmlElement; if (elem != null) id = elem.GetAttribute(Help2Attr.Value); if (string.IsNullOrEmpty(locale)) { elem = _xml.SelectSingleNode(string.Format(Help2XPath.Attr, Help2Value.Locale), nsmgr) as XmlElement; if (elem != null) locale = elem.GetAttribute(Help2Attr.Value); } } if (string.IsNullOrEmpty(locale)) locale = MHSDefault.Locale; AddMHSMeta(MHSMetaName.Locale, locale); AddMHSMeta(MHSMetaName.TopicLocale, locale); AddMHSMeta(MHSMetaName.Id, id); if (_toc.ContainsKey(id)) { TocInfo tocInfo = _toc[id]; AddMHSMeta(MHSMetaName.TocParent, tocInfo.Parent); if (tocInfo.Parent != MHSDefault.TocParent) AddMHSMeta(MHSMetaName.TocParentVersion, tocInfo.ParentVersion); AddMHSMeta(MHSMetaName.TocOrder, tocInfo.Order.ToString()); } }
private Rpc2DocumentLiteralTranslator(XmlDocument wsdl) { xdoc = wsdl; nsmgr = new XmlNamespaceManager(xdoc.NameTable); XmlElement root = (XmlElement) xdoc.DocumentElement; foreach (XmlAttribute a in root.Attributes) { if (a.Prefix == "xmlns") { Trace.WriteLine(a.LocalName + " = " + a.Value); nsmgr.AddNamespace(a.LocalName, a.Value); } if (a.Name == "targetNamespace") { targetNamespace = a.Value; } } if (nsmgr.HasNamespace("wsdl") == false) { nsmgr.AddNamespace("wsdl", "http://schemas.xmlsoap.org/wsdl/"); } if (nsmgr.HasNamespace("xsd") == false) { nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); } if (nsmgr.HasNamespace("soap") == false) { nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/wsdl/soap/"); } BuildItems(nsmgr); }
/// <summary> /// Parses an XMLDocument and returns an XML namespace manager. /// </summary> /// <param name="document">The document.</param> /// <param name="log">The log.</param> /// <returns></returns> private static XmlNamespaceManager ParseAndReturnXmlNamespaceManager(XmlDocument document, IRenderConfigLogger log) { Regex namespaces = new Regex(@"xmlns:?(?<ns>[a-zA-Z]*)=""(?<url>((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*))"""); MatchCollection matches = namespaces.Matches(document.OuterXml); XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable); if (matches.Count > 0) { foreach (Match match in matches) { if (!manager.HasNamespace(match.Groups["ns"].ToString())) { //We will use "r" as our pretend namespace string ns = "r"; if (!String.IsNullOrEmpty(match.Groups["ns"].Value)) { ns = match.Groups["ns"].ToString(); } log.LogMessage(MessageImportance.High, string.Concat("Adding XML Namespace : ".PadLeft(27) + ns + " = " + match.Groups["url"])); manager.AddNamespace(ns, match.Groups["url"].ToString()); } } } return manager; }
/// <summary> /// Checks and modifies the XPath namespace. /// </summary> /// <param name="xpath">The xpath.</param> /// <param name="manager">The manager.</param> /// <returns></returns> private static string ModifyXPathWithNamespace(string xpath, XmlNamespaceManager manager) { if (manager.HasNamespace("r")) { string newXpath = string.Empty; string[] xpathArray = SplitXPathIntelligently(xpath); foreach (string s in xpathArray) { if (!string.IsNullOrEmpty(s)) { if (s.StartsWith("@")) { newXpath = string.Concat(newXpath, "/", s); } else { if (!xpath.StartsWith("/")) { newXpath = string.Concat(newXpath, "r:", s); } else { newXpath = string.Concat(newXpath, "/r:", s); } } } } return newXpath; } else { return xpath; } }
private void AddNamespaceFromNode(XmlNodeList nodes, XmlNamespaceManager namespaceManager) { foreach (XmlNode node in nodes) { if (!string.IsNullOrEmpty(node.Prefix)) { if (!namespaceManager.HasNamespace(node.Prefix)) namespaceManager.AddNamespace(node.Prefix, node.GetNamespaceOfPrefix(node.Prefix)); } else if (node.Attributes != null) { if (node.Attributes.Count > 0) { foreach (XmlAttribute attribute in node.Attributes) { //if it is a namespace attribute, then we'll add it if (attribute.Name.ToLower().StartsWith("xmlns:")) { if (!namespaceManager.HasNamespace(attribute.LocalName)) namespaceManager.AddNamespace(attribute.LocalName, attribute.Value); } } } } if (node.HasChildNodes) AddNamespaceFromNode(node.ChildNodes, namespaceManager); } }