BExIS.Xml.Helpers.XExtentsions.GetAbsoluteXPath C# (CSharp) Метод

GetAbsoluteXPath() публичный статический Метод

Get the absolute XPath to a given XElement, including the namespace. (e.g. "/a:people/b:person[6]/c:name[1]/d:last[1]").
public static GetAbsoluteXPath ( this element ) : string
element this
Результат string
        public static string GetAbsoluteXPath(this XElement element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            Func<XElement, string> relativeXPath = e =>
            {
                int index = e.IndexPosition();

                var currentNamespace = e.Name.Namespace;

                string name = "";
                if (currentNamespace == null)
                {
                    name = e.Name.LocalName;
                }
                else
                {
                    //string namespacePrefix = e.GetPrefixOfNamespace(currentNamespace);
                    name += "/"+ e.Name.LocalName;
                }

                return name;
                // If the element is the root, no index is required
                //return (index == -1) ? "/" + name : string.Format
                //(
                //    "/{0}[{1}]",
                //    name,
                //    index.ToString()
                //);
            };

            var ancestors = from e in element.Ancestors()
                            select relativeXPath(e);

            return string.Concat(ancestors.Reverse().ToArray()) +
                   relativeXPath(element);
        }

Usage Example

Пример #1
0
        /// <summary>
        /// Returns a List of SearchMetadataNode
        /// for each Metadata Simple Attribute
        /// </summary>
        /// <param name="id">Metadata Structure Id</param>
        /// <returns> List<SearchMetadataNode> </returns>
        public List <SearchMetadataNode> GetAllXPathsOfSimpleAttributes(long id)
        {
            List <SearchMetadataNode> list = new List <SearchMetadataNode>();

            // load metadatastructure with all packages and attributes

            using (var uow = this.GetUnitOfWork())
            {
                string title = uow.GetReadOnlyRepository <MetadataStructure>().Get(id).Name;

                XmlMetadataWriter xmlMetadatWriter = new XmlMetadataWriter(XmlNodeMode.xPath);
                XDocument         metadataXml      = xmlMetadatWriter.CreateMetadataXml(id);

                List <XElement> elements = metadataXml.Root.Descendants().Where(e => e.HasElements.Equals(false)).ToList();

                foreach (XElement element in elements)
                {
                    list.Add(
                        new SearchMetadataNode(title, XExtentsions.GetAbsoluteXPath(element).Substring(1))
                        );
                }

                return(list);
            }
        }