/// <summary> /// Compacts the path so it only contains the elements that are from /// the namespace of the last element in the path. /// </summary> /// <remarks>This method is used when we need to know the path for a /// particular namespace and do not care about the complete path. /// </remarks> public void Compact() { if (elements.HasItems) { XmlElementQualifiedName lastName = Elements.GetLast(); int index = LastIndexNotMatchingNamespace(lastName.Namespace); if (index != -1) { elements.RemoveFirst(index + 1); } } }
int LastIndexNotMatchingNamespace(string namespaceUri) { if (elements.Count > 1) { // Start the check from the last but one item. for (int i = elements.Count - 2; i >= 0; --i) { XmlElementQualifiedName name = elements[i]; if (name.Namespace != namespaceUri) { return(i); } } } return(-1); }
public void AddElement(XmlElementQualifiedName elementName) { elements.Add(elementName); }
/// <summary> /// Source: SharpDevelop /// </summary> /// <param name="xml"></param> /// <returns></returns> public static XmlElementInformation GetParentElementPath(string xml) { XmlElementInformation path = new XmlElementInformation(); IDictionary<string, string> namespacesInScope = null; using (StringReader reader = new StringReader(xml)) { using (XmlTextReader xmlReader = new XmlTextReader(reader)) { try { xmlReader.XmlResolver = null; // prevent XmlTextReader from loading external DTDs while (xmlReader.Read()) { switch (xmlReader.NodeType) { case XmlNodeType.Element: if (!xmlReader.IsEmptyElement) { XmlElementQualifiedName elementName = new XmlElementQualifiedName(xmlReader.LocalName, xmlReader.NamespaceURI, xmlReader.Prefix); path.AddElement(elementName); } break; case XmlNodeType.EndElement: path.Elements.RemoveLast(); break; } } } catch (XmlException) { namespacesInScope = xmlReader.GetNamespacesInScope(XmlNamespaceScope.All); } } } // Add namespaces in scope for the last element read. if (namespacesInScope != null) { foreach (KeyValuePair<string, string> ns in namespacesInScope) { path.NamespacesInScope.Add(new XmlNamespace(ns.Key, ns.Value)); } } return path; }