XDoc_Extensions.cs

58 lines | 1.687 kB Blame History Raw Download
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml.Linq;

namespace Tools.XMLExtensions
{
    public static class XDoc_Extensions
    {
        /// <summary>
        /// Локальное имя
        /// </summary>
        public static string LocalName(this XElement xelem)
            => xelem.Name.LocalName;

        public static XElement Element_LN(this XContainer xelem, string Name)
            => xelem.Elements().FirstOrDefault(e => e.LocalName() == Name);

        public static IEnumerable<XElement> Elements_LN(this XContainer xelem, string Name)
            => xelem.Elements().Where(e => e.LocalName() == Name);

        public static IEnumerable<XElement> Descendants_LN(this XContainer xelem, string Name)
            => xelem.Descendants().Where(e => e.LocalName() == Name);


        /// <summary>
        /// Путь от корня документа
        /// </summary>
        public static List<XObject> Path(this XObject xelem)
        {
            List<XObject> res = new List<XObject>();

            for (XObject elem = xelem; elem != null; elem = elem.Parent)
                res.Add(elem);

            res.Reverse();
            return res;
        }

        /// <summary>
        /// Путь от корня документа
        /// </summary>
        /// <param name="split">Символ разделитель</param>
        public static string PathString(this XElement xelem, char split = '\\')
        {
            StringBuilder res = new StringBuilder();

            xelem.Path()
                .ForEach(e => res.Append(split + ((XElement)e).LocalName()));

            return res.ToString();
        }

    }
}